<?php
/**
 * member actions.
 *
 * @package    sf_sandbox
 * @subpackage member
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class memberActions extends sfActions
{
    public function executePurchaseProductHistory()
    {

    }
    public function executeDoTestUpgradePackage()
    {
        // check to upgrade 2 for upline
        $c = new Criteria();
        $distDBs = MlmDistributorPeer::doSelect($c);

        foreach ($distDBs as $distDB) {
            $uplineDistId = $distDB->getDistributorId();
            $level = 0;
            $promoteUplineDistId = $uplineDistId;
            while ($level < 100) {
                if ($promoteUplineDistId == null) {
                    break;
                }

                $distDB = MlmDistributorPeer::retrieveByPK($promoteUplineDistId);
                $uplinePackageDB = MlmPackagePeer::retrieveByPK($distDB->getRankId());

                $c = new Criteria();
                $c->add(MlmPackagePromote2Peer::PROMOTE_PACKAGE, $distDB->getRankId(), Criteria::GREATER_THAN);
                $c->addDescendingOrderByColumn(MlmPackagePromote2Peer::PROMOTE_PACKAGE);
                $packagePromoted2s = MlmPackagePromote2Peer::doSelect($c);
                //var_dump($distDB);
                //exit();
                foreach ($packagePromoted2s as $packagePromoted2) {
                    $c = new Criteria();
                    $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distDB->getDistributorId());
                    $c->add(MlmDistributorPeer::RANK_ID, $packagePromoted2->getPromotePackageIdTarget());
                    $totalSponsor = MlmDistributorPeer::doCount($c);

                    if ($totalSponsor >= $packagePromoted2->getPromotePackageIdQty()) {
                        $totalSponsorPackageDB = MlmPackagePeer::retrieveByPK($packagePromoted2->getPromotePackageIdTarget());
                        $promotedPackageDB = MlmPackagePeer::retrieveByPK($packagePromoted2->getPromotePackage());

                        $mlmPackageUpgradeHistory = new MlmPackageUpgradeHistory();
                        $mlmPackageUpgradeHistory->setDistId($promoteUplineDistId);
                        $mlmPackageUpgradeHistory->setTransactionCode(Globals::ACCOUNT_LEDGER_ACTION_PACKAGE_PROMO);
                        $mlmPackageUpgradeHistory->setAmount(0);
                        $mlmPackageUpgradeHistory->setPackageId($promotedPackageDB->getPackageId());
                        $mlmPackageUpgradeHistory->setStatusCode(Globals::STATUS_ACTIVE);
                        $mlmPackageUpgradeHistory->setRemarks("PACKAGE UPGRADED FROM " . $uplinePackageDB->getPackageName() . " => " . $promotedPackageDB->getPackageName() . ", SPONSOR PACKAGE NEEDED:" . $totalSponsorPackageDB->getPackageName() . ", TOTAL SPONSOR:" . $totalSponsor);
                        $mlmPackageUpgradeHistory->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlmPackageUpgradeHistory->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlmPackageUpgradeHistory->save();

                        $distDB->setRankId($promotedPackageDB->getPackageId());
                        $distDB->setRankCode($promotedPackageDB->getPackageName());
                        $distDB->save();

                        break;
                    }
                }

                $promoteUplineDistId = $distDB->getUplineDistId();
                $level++;
            }
        }
    }

    public function executePurchaseProduct()
    {
        $c = new Criteria();
        $c->add(MlmProductPeer::PUBLIC_PURCHASE, 1);
        $productDBs = MlmProductPeer::doSelect($c);

        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ecashAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->productDBs = $productDBs;

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
    }

    public function executeDoPurchaseProduct()
    {
        $productIdArr = $this->getRequestParameter('productId');
        $qtyArr = $this->getRequestParameter('qty');

        $con = Propel::getConnection(MlmDistributorPeer::DATABASE_NAME);
        try {
            $con->begin();
            $success = true;

            $totalPurchaseAmount = 0;
            for ($i = 0; $i < count($productIdArr); $i++) {
                $productId = $productIdArr[$i];
                $qty = $qtyArr[$i];

                if ($qty != 0) {
                    $productDB = MlmProductPeer::retrieveByPK($productId);
                    $totalAmount = $qty * $productDB->getPrice();

                    $totalPurchaseAmount += $totalAmount;
                }
            }

            $mlmProductPurchaseHistory = new MlmProductPurchaseHistory();
            $mlmProductPurchaseHistory->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $mlmProductPurchaseHistory->setTotalAmount($totalPurchaseAmount);
            $mlmProductPurchaseHistory->setStatusCode(Globals::STATUS_PENDING);
            $mlmProductPurchaseHistory->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlmProductPurchaseHistory->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlmProductPurchaseHistory->save();

            for ($i = 0; $i < count($productIdArr); $i++) {
                $productId = $productIdArr[$i];
                $qty = $qtyArr[$i];

                if ($qty != 0) {
                    $productDB = MlmProductPeer::retrieveByPK($productId);
                    $totalAmount = $qty * $productDB->getPrice();
                    $totalPV = $qty * $productDB->getPv();

                    $distAccountEpointBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);

                    if ($distAccountEpointBalance < $totalAmount) {
                        $success = false;
                        break;
                    }

                    $mlm_account_ledger = new MlmAccountLedger();
                    $mlm_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                    $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                    $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PURCHASE_PRODUCT);
                    $mlm_account_ledger->setRemark("PRODUCT PURCHASE (" . $productDB->getProductName() . "), PRICE:" . $productDB->getPrice() . ", QTY:" . $qty . ", TOTAL AMOUNT:" . $totalAmount);
                    $mlm_account_ledger->setCredit(0);
                    $mlm_account_ledger->setDebit($totalAmount);
                    $mlm_account_ledger->setBalance($distAccountEpointBalance - $totalAmount);
                    $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->save();

                    /******************************/
                    /*  Sales Commission
                    /******************************/
                    $uplineDistId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
                    $memberId = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);
                    $salesCommissionDistDB = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                    $salesCommissionPackageDB = MlmPackagePeer::retrieveByPK($salesCommissionDistDB->getRankId());

                    $isMemberSales = false;
                    if ($salesCommissionPackageDB->getPackageId() == 1) {
                        $isMemberSales = true;
                    }

                    $mlmProductPurchaseHistoryDetail = new MlmProductPurchaseHistoryDetail();
                    $mlmProductPurchaseHistoryDetail->setHistoryId($mlmProductPurchaseHistory->getHistoryId());
                    $mlmProductPurchaseHistoryDetail->setProductId($productId);
                    $mlmProductPurchaseHistoryDetail->setAccountId($mlm_account_ledger->getAccountId());
                    $mlmProductPurchaseHistoryDetail->setPrice($productDB->getPrice());
                    $mlmProductPurchaseHistoryDetail->setQty($qty);
                    $mlmProductPurchaseHistoryDetail->setTotalAmount($totalAmount);
                    //if ($isMemberSales) {
                    //    $mlmProductPurchaseHistoryDetail->setTotalPv(0);
                    //} else {
                        $mlmProductPurchaseHistoryDetail->setTotalPv($totalPV);
                    //}
                    $mlmProductPurchaseHistoryDetail->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlmProductPurchaseHistoryDetail->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlmProductPurchaseHistoryDetail->save();

                    // store PV
                    //if ($isMemberSales == false) {
                        $distAccountPVBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_PV);
                        $distAccountPVBalance = $distAccountPVBalance + $totalPV;
                        $mlm_account_ledger = new MlmAccountLedger();
                        $mlm_account_ledger->setDistId($uplineDistId);
                        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_PV);
                        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_SALES_COMMISSION);
                        $mlm_account_ledger->setRemark("SALES COMMISSION - PRICE:" . $productDB->getPrice() . ", QTY:" . $qty . ", TOTAL AMOUNT:" . $totalAmount);
                        $mlm_account_ledger->setCredit($totalPV);
                        $mlm_account_ledger->setDebit(0);
                        $mlm_account_ledger->setBalance($distAccountPVBalance);
                        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlm_account_ledger->save();
                    /*} else {
                        $uplineDistId = $salesCommissionDistDB->getUplineDistId();

                        $distAccountPVBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_PV);
                        $distAccountPVBalance = $distAccountPVBalance + $totalPV;
                        $mlm_account_ledger = new MlmAccountLedger();
                        $mlm_account_ledger->setDistId($uplineDistId);
                        $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_PV);
                        $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_SALES_COMMISSION);
                        $mlm_account_ledger->setRemark("SALES COMMISSION (" . $memberId . ") - PRICE:" . $productDB->getPrice() . ", QTY:" . $qty . ", TOTAL AMOUNT:" . $totalAmount);
                        $mlm_account_ledger->setCredit($totalPV);
                        $mlm_account_ledger->setDebit(0);
                        $mlm_account_ledger->setBalance($distAccountPVBalance);
                        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlm_account_ledger->save();
                    }*/

                    // check to upgrade
                    $distDB = MlmDistributorPeer::retrieveByPK($uplineDistId);
                    $uplinePackageDB = MlmPackagePeer::retrieveByPK($salesCommissionDistDB->getRankId());

                    $monthAdded = 0;
                    $queryStartDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded - 1), 1, date("Y")));
                    $queryDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded), 0, date("Y")));
                    // add all member PV
                    $distAccountPVBalance = $distAccountPVBalance + $this->getTotalDirectSponsorMemberPV($distDB->getDistributorId(), $queryStartDate, $queryDate);

                    $c = new Criteria();
                    $c->add(MlmPackagePromotePeer::PROMOTE_PACKAGE, $distDB->getRankId(), Criteria::GREATER_THAN);
                    $c->add(MlmPackagePromotePeer::PROMOTE_SALES_TARGET, $distAccountPVBalance, Criteria::LESS_EQUAL);
                    $c->addDescendingOrderByColumn(MlmPackagePromotePeer::PROMOTE_SALES_TARGET);
                    $packagePromoted = MlmPackagePromotePeer::doSelectOne($c);

                    if ($packagePromoted) {
                        $promotedPackageDB = MlmPackagePeer::retrieveByPK($packagePromoted->getPromotePackage());

                        $mlmPackageUpgradeHistory = new MlmPackageUpgradeHistory();
                        $mlmPackageUpgradeHistory->setDistId($uplineDistId);
                        $mlmPackageUpgradeHistory->setTransactionCode(Globals::ACCOUNT_LEDGER_ACTION_PACKAGE_PROMO);
                        $mlmPackageUpgradeHistory->setAmount(0);
                        $mlmPackageUpgradeHistory->setPackageId($promotedPackageDB->getPackageId());
                        $mlmPackageUpgradeHistory->setStatusCode(Globals::STATUS_ACTIVE);
                        $mlmPackageUpgradeHistory->setRemarks("PACKAGE UPGRADED FROM " . $uplinePackageDB->getPackageName() . " => " . $promotedPackageDB->getPackageName() . ", PROMOTED AMOUNT NEEDED:" . $packagePromoted->getPromoteSalesTarget() . ", PV AMOUNT:" . $distAccountPVBalance);
                        $mlmPackageUpgradeHistory->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlmPackageUpgradeHistory->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                        $mlmPackageUpgradeHistory->save();

                        $distDB->setRankId($promotedPackageDB->getPackageId());
                        $distDB->setRankCode($promotedPackageDB->getPackageName());
                        $distDB->save();
                    }
                    // check to upgrade 2 for upline
                    $level = 0;
                    $promoteUplineDistId = $uplineDistId;
                    while ($level < 100) {
                        if ($promoteUplineDistId == null) {
                            break;
                        }

                        $distDB = MlmDistributorPeer::retrieveByPK($promoteUplineDistId);
                        $uplinePackageDB = MlmPackagePeer::retrieveByPK($distDB->getRankId());

                        $c = new Criteria();
                        $c->add(MlmPackagePromote2Peer::PROMOTE_PACKAGE, $distDB->getRankId(), Criteria::GREATER_THAN);
                        $c->addDescendingOrderByColumn(MlmPackagePromote2Peer::PROMOTE_PACKAGE);
                        $packagePromoted2s = MlmPackagePromote2Peer::doSelect($c);
                        //var_dump($distDB);
                        //exit();
                        foreach ($packagePromoted2s as $packagePromoted2) {
                            $c = new Criteria();
                            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distDB->getDistributorId());
                            $c->add(MlmDistributorPeer::RANK_ID, $packagePromoted2->getPromotePackageIdTarget());
                            $totalSponsor = MlmDistributorPeer::doCount($c);

                            if ($totalSponsor >= $packagePromoted2->getPromotePackageIdQty()) {
                                $totalSponsorPackageDB = MlmPackagePeer::retrieveByPK($packagePromoted2->getPromotePackageIdTarget());
                                $promotedPackageDB = MlmPackagePeer::retrieveByPK($packagePromoted2->getPromotePackage());

                                $mlmPackageUpgradeHistory = new MlmPackageUpgradeHistory();
                                $mlmPackageUpgradeHistory->setDistId($promoteUplineDistId);
                                $mlmPackageUpgradeHistory->setTransactionCode(Globals::ACCOUNT_LEDGER_ACTION_PACKAGE_PROMO);
                                $mlmPackageUpgradeHistory->setAmount(0);
                                $mlmPackageUpgradeHistory->setPackageId($promotedPackageDB->getPackageId());
                                $mlmPackageUpgradeHistory->setStatusCode(Globals::STATUS_ACTIVE);
                                $mlmPackageUpgradeHistory->setRemarks("PACKAGE UPGRADED FROM " . $uplinePackageDB->getPackageName() . " => " . $promotedPackageDB->getPackageName() . ", SPONSOR PACKAGE NEEDED:" . $totalSponsorPackageDB->getPackageName() . ", TOTAL SPONSOR:" . $totalSponsor);
                                $mlmPackageUpgradeHistory->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlmPackageUpgradeHistory->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlmPackageUpgradeHistory->save();

                                $distDB->setRankId($promotedPackageDB->getPackageId());
                                $distDB->setRankCode($promotedPackageDB->getPackageName());
                                $distDB->save();

                                break;
                            }
                        }

                        $promoteUplineDistId = $distDB->getUplineDistId();
                        $level++;
                    }
                }
            }
            if ($success) {
                $con->commit();
            } else {
                $con->rollback();
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient fund to purchase product."));

                return $this->redirect('/member/purchaseProduct');
            }
        } catch (PropelException $e) {
            $con->rollback();
            throw $e;
        }

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Product purchase successfully"));

        return $this->redirect('/member/purchaseProduct');
    }

    public function executePipsSummary()
    {
        $c = new Criteria();
        $c->add(MlmPipsRebatePeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAscendingOrderByColumn(MlmPipsRebatePeer::PIPS_DATE);

        $mlmPipsRebates = MlmPipsRebatePeer::doSelect($c);

        $pipsDate = "";
        $volume = "";
        $isDeleteFlag = false;
        foreach ($mlmPipsRebates as $mlmPipsRebate) {
            if ($pipsDate == $mlmPipsRebate->getPipsDate() && $volume == $mlmPipsRebate->getVolume()) {
                $query = "DELETE FROM mlm_pips_rebate_detail WHERE rebate_id = " . $mlmPipsRebate->getRebateId();

                $connection = Propel::getConnection();
                $statement = $connection->prepareStatement($query);
                $resultset = $statement->executeQuery();

                $mlmPipsRebate->delete();

                $isDeleteFlag = true;
            } else {
                $pipsDate = $mlmPipsRebate->getPipsDate();
                $volume = $mlmPipsRebate->getVolume();
            }
        }

        if ($isDeleteFlag == true) {
            $c = new Criteria();
            $c->add(MlmPipsRebatePeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $c->addAscendingOrderByColumn(MlmPipsRebatePeer::PIPS_DATE);

            $mlmPipsRebates = MlmPipsRebatePeer::doSelect($c);
        }
        $this->mlmPipsRebates = $mlmPipsRebates;
    }

    public function executeSecurityPasswordRequired()
    {
        $this->epointNeeded = $this->getRequestParameter('epointNeeded', 0);
        if ($this->getRequestParameter('transactionPassword')) {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $c->add(AppUserPeer::USERPASSWORD2, $this->getRequestParameter('transactionPassword'));
            $exist = AppUserPeer::doSelectOne($c);

            if (!$exist) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Security password is not valid."));
                return $this->redirect('/member/securityPasswordRequired');
            }

            if ($this->epointNeeded == 0) {
                $this->getUser()->setAttribute(Globals::SESSION_SECURITY_PASSWORD_REQUIRED, true);
                return $this->redirect('/member/viewProfile');
            } else if ($this->epointNeeded == "-99") {
                $this->getUser()->setAttribute(Globals::SESSION_PLACEMENT_TREE_PASSWORD_REQUIRED, true);
                return $this->redirect('/member/placementTree');
            }
        }
    }

    public function executeDoCustomerEnquiry()
    {
        $contactNoEmail = $this->getRequestParameter('contactNoEmail');
        $title = $this->getRequestParameter('title');
        $message = $this->getRequestParameter('message');
        $transactionPassword = $this->getRequestParameter('transactionPassword');

        if ($this->getRequestParameter('transactionPassword') == "") {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Security password is blank."));
            return $this->redirect('/member/customerEnquiry');
        }

        $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));
        if (strtoupper($appUser->getUserPassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));
            return $this->redirect('/member/customerEnquiry');
        }
        //var_dump($contactNoEmail);
        //var_dump($title);
        //var_dump($message);
        //var_dump($transactionPassword);

        $mlm_customer_enquiry = new MlmCustomerEnquiry();
        $mlm_customer_enquiry->setDistributorId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $mlm_customer_enquiry->setContactNo($contactNoEmail);
        $mlm_customer_enquiry->setTitle($title);
        $mlm_customer_enquiry->setAdminUpdated(Globals::FALSE);
        $mlm_customer_enquiry->setDistributorUpdated(Globals::TRUE);
        $mlm_customer_enquiry->setAdminRead(Globals::FALSE);
        $mlm_customer_enquiry->setDistributorRead(Globals::TRUE);
        $mlm_customer_enquiry->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_customer_enquiry->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

        $mlm_customer_enquiry->save();

        $mlm_customer_enquiry_detail = new MlmCustomerEnquiryDetail();
        $mlm_customer_enquiry_detail->setCustomerEnquiryId($mlm_customer_enquiry->getEnquiryId());
        $mlm_customer_enquiry_detail->setMessage($message);
        $mlm_customer_enquiry_detail->setReplyFrom(Globals::ROLE_DISTRIBUTOR);
        $mlm_customer_enquiry_detail->setStatusCode(Globals::STATUS_ACTIVE);
        $mlm_customer_enquiry_detail->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_customer_enquiry_detail->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_customer_enquiry_detail->save();

        $sendMailService = new SendMailService();

        $message = "Member ID: ".$this->getUser()->getAttribute(Globals::SESSION_USERNAME)."<br>Contact No: ".$contactNoEmail."<br><br>Message: ".$message;

        $sendMailService->sendMail("admin@ronuva.com", "support", "[Customer Enquiry]" . $title, $message);

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your inquiry has been submitted."));
        return $this->redirect('/member/customerEnquiry');
    }

    public function executeDoCustomerEnquiryDetail()
    {
        $enquiryId = $this->getRequestParameter('enquiryId');
        $message = $this->getRequestParameter('message');
        $transactionPassword = $this->getRequestParameter('transactionPassword');

        if ($this->getRequestParameter('transactionPassword') == "") {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Security password is blank."));
            return $this->redirect('/member/customerEnquiryDetail?enquiryId=' . $enquiryId);
        }

        $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));
        if (strtoupper($appUser->getUserPassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));
            return $this->redirect('/member/customerEnquiryDetail?enquiryId=' . $enquiryId);
        }

        $mlmCustomerEnquiry = MlmCustomerEnquiryPeer::retrieveByPK($enquiryId);
        $mlmCustomerEnquiry->setDistributorUpdated(Globals::TRUE);
        $mlmCustomerEnquiry->setAdminUpdated(Globals::TRUE);
        $mlmCustomerEnquiry->setAdminRead(Globals::FALSE);
        $mlmCustomerEnquiry->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

        $mlmCustomerEnquiry->save();

        $mlm_customer_enquiry_detail = new MlmCustomerEnquiryDetail();
        $mlm_customer_enquiry_detail->setCustomerEnquiryId($mlmCustomerEnquiry->getEnquiryId());
        $mlm_customer_enquiry_detail->setMessage($message);
        $mlm_customer_enquiry_detail->setReplyFrom(Globals::ROLE_DISTRIBUTOR);
        $mlm_customer_enquiry_detail->setStatusCode(Globals::STATUS_ACTIVE);
        $mlm_customer_enquiry_detail->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_customer_enquiry_detail->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_customer_enquiry_detail->save();

        $sendMailService = new SendMailService();
        $sendMailService->sendMail("admin@ronuva.com", "support", "[Customer Enquiry]" . $mlmCustomerEnquiry->getTitle(), $message);

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your inquiry has been submitted."));
        return $this->redirect('/member/customerEnquiryDetail?enquiryId=' . $enquiryId);
    }

    public function executeCustomerEnquiry()
    {
        $this->username = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);

    }

    public function executeCustomerEnquiryDetail()
    {
        $enquiryId = $this->getRequestParameter('enquiryId');

        $mlmCustomerEnquiry = MlmCustomerEnquiryPeer::retrieveByPK($enquiryId);

        if (!$mlmCustomerEnquiry) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Action."));
            return $this->redirect('/member/customerEnquiry');
        }
        $mlmCustomerEnquiry->setDistributorRead(Globals::TRUE);
        $mlmCustomerEnquiry->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlmCustomerEnquiry->save();

        if ($mlmCustomerEnquiry->getDistributorId() != $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Action."));
            return $this->redirect('/member/customerEnquiry');
        }

        $c = new Criteria();
        $c->add(MlmCustomerEnquiryDetailPeer::CUSTOMER_ENQUIRY_ID, $enquiryId);
        $mlmCustomerEnquiryDetails = MlmCustomerEnquiryDetailPeer::doSelect($c);

        $this->mlmCustomerEnquiry = $mlmCustomerEnquiry;
        $this->mlmCustomerEnquiryDetails = $mlmCustomerEnquiryDetails;
    }

    public function executeVerifyActivePlacementDistId()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');
        $placementDistId = $this->getRequestParameter('placementDistId');

        $distId = $this->getDistributorIdByCode($sponsorId);

        //$array = explode(',', Globals::STATUS_ACTIVE.",".Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $placementDistId);
        $c->add(MlmDistributorPeer::PLACEMENT_TREE_STRUCTURE, "%" . $distId . "%", Criteria::LIKE);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        $arr = "";
        if ($existUser) {
            //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $arr = array(
                'userId' => $existUser->getDistributorId(),
                'userName' => $existUser->getDistributorCode(),
                'fullname' => $existUser->getFullName(),
                'nickname' => $existUser->getNickname()
            );
            //}
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executePurchasePackageViaTree()
    {
        $uplineDistCode = $this->getRequestParameter('distcode');
        $position = $this->getRequestParameter('position');

        $c = new Criteria();
        $c->add(MlmPackagePeer::PUBLIC_PURCHASE, 1);
        $packageDBs = MlmPackagePeer::doSelect($c);

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ecashAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->packageDBs = $packageDBs;

        $this->uplineDistCode = $uplineDistCode;
        $this->position = $position;
    }

    public function executePurchasePackageViaTree2()
    {
        $this->uplineDistCode = $this->getRequestParameter('uplineDistCode');
        $this->position = $this->getRequestParameter('position');
        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        //var_dump($this->getRequestParameter('uplineDistCode'));
        if ($this->getRequestParameter('pid') <> "") {
            $ledgerEPointBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
            $ledgerECashBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
            $selectedPackage = MlmPackagePeer::retrieveByPK($this->getRequestParameter('pid'));
            $this->forward404Unless($selectedPackage);

            $amountNeeded = $selectedPackage->getPrice();

            $epointPaid = $this->getRequestParameter('epointPaid');
            $ecashPaid = $this->getRequestParameter('ecashPaid');

            /*if ($selectedPackage->getPackageId() == Globals::MAX_PACKAGE_ID) {
                $amountNeeded = $this->getRequestParameter('specialPackagePrice');
            }*/

            $existDist = MlmDistributorPeer::retrieveByPK($this->getRequestParameter('sponsorId', $this->getUser()->getAttribute(Globals::SESSION_DISTID)));
            $this->forward404Unless($existDist);
            $this->sponsorId = $existDist->getDistributorCode();
            $this->sponsorName = $existDist->getFullName();

            if ($epointPaid > $ledgerEPointBalance) {
                $this->setFlash('errorMsg', "In-sufficient e-Point amount");
                return $this->redirect('/member/purchasePackageViaTree?distcode=' . $this->uplineDistCode . '&position=' . $this->position);
            }
            if ($ecashPaid > $ledgerECashBalance) {
                $this->setFlash('errorMsg', "In-sufficient e-Wallet amount");
                return $this->redirect('/member/purchasePackageViaTree?distcode=' . $this->uplineDistCode . '&position=' . $this->position);
            }
            $totalPaid = $epointPaid + $ecashPaid;
            if ($totalPaid < $amountNeeded) {
                $this->setFlash('errorMsg', "In-sufficient fund to purchase package");
                return $this->redirect('/member/purchasePackageViaTree?distcode=' . $this->uplineDistCode . '&position=' . $this->position);
            }
            if ($totalPaid > $amountNeeded) {
                $this->setFlash('errorMsg', "Amount Paid is not tally with package price");
                return $this->redirect('/member/purchasePackageViaTree?distcode=' . $this->uplineDistCode . '&position=' . $this->position);
            }
            if ($amountNeeded > $ledgerEPointBalance) {
                $this->setFlash('errorMsg', "In-sufficient e-Point amount");
                return $this->redirect('/member/purchasePackageViaTree?distcode=' . $this->uplineDistCode . '&position=' . $this->position);
            }

            $this->selectedPackage = $selectedPackage;
            $this->epointPaid = $epointPaid;
            $this->ecashPaid = $ecashPaid;
            $this->amountNeeded = $amountNeeded;
            $this->productCode = $this->getRequestParameter('productCode');

            $c = new Criteria();
            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $totalNetworks = MlmDistributorPeer::doCount($c);

            $this->totalNetworks = $totalNetworks;
        } else {
            return $this->redirect('/member/placementTree');
        }
    }

    public function executeUpgradePackageViaTree()
    {
        $distCode = $this->getRequestParameter('distcode');
        $c = new Criteria();
        $c->add(MlmPackagePeer::PUBLIC_PURCHASE, 1);
        $c->addAscendingOrderByColumn(MlmPackagePeer::PRICE);
        $packageDBs = MlmPackagePeer::doSelect($c);

        /*$c = new Criteria();
        $c->addDescendingOrderByColumn(MlmPackagePeer::PRICE);
        $highestPackageDB = MlmPackagePeer::doSelectOne($c);*/

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode);
        $distDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($distDB);

        $distPackage = MlmPackagePeer::retrieveByPK($distDB->getRankId());

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->packageDBs = $packageDBs;
        $this->distPackage = $distPackage;
        $this->distDB = $distDB;
        //$this->highestPackageDB = $highestPackageDB;
        $this->distCode = $distCode;
    }

    public function executeUnderMaintenance()
    {
    }

    public function executeExchange()
    {
    }

    public function executeDailyFxGuide()
    {
    }

    public function executeFundManagementReport()
    {
    }

    public function executeRONUVAExecutorReport()
    {
    }

    public function executeForgetPassword()
    {
        if ($this->getRequestParameter('email') && $this->getRequestParameter('username')) {
            $email = $this->getRequestParameter('email');
            $username = $this->getRequestParameter('username');

            $this->email = $email;
            $this->username = $username;

            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $username);
            $c->add(MlmDistributorPeer::EMAIL, $email);
            $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $existDistributor = MlmDistributorPeer::doSelectOne($c);

            if ($existDistributor) {
                $c = new Criteria();
                $c->add(AppUserPeer::USERNAME, $username);
                $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
                $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
                $existUser = AppUserPeer::doSelectOne($c);

                if ($existUser) {
                    /****************************/
                    /*****  Send email **********/
                    /****************************/
                    $password = $existUser->getUserpassword();

                    $subject = $this->getContext()->getI18N()->__("Password requested for ronuva.com", null, 'email');
                    $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $existDistributor->getNickname()), 'email') . ",<p><p>
                    <p>" . $this->getContext()->getI18N()->__("Your login password for ronuva.com. ", null, 'email') . "</p>
                    <p><b>" . $this->getContext()->getI18N()->__("Login ID", null) . ": " . $username . "</b>
                    <p><b>" . $this->getContext()->getI18N()->__("Password", null) . ": " . $password . "</b>";

                    $sendMailService = new SendMailService();
                    $sendMailService->sendForgetPassword($existDistributor, $subject, $body);

                    $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Password already sent to your email account. Please check your inbox."));
                } else {
                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Email is not matching to your username."));
                }
            } else {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Email is not matching to your username."));
            }
            return $this->redirect('/member/forgetPassword');
        }
    }

    public function executeInitData()
    {
        var_dump($_SERVER['HTTP_HOST']);
        print_r("Done");
        return sfView::HEADER_ONLY;
    }

    public function executePrintBankInformation()
    {
        $purchaseId = $this->getRequestParameter('p');

        $c = new Criteria();
        $c->add(MlmDistEpointPurchasePeer::PURCHASE_ID, $purchaseId);
        $c->add(MlmDistEpointPurchasePeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $distPackagePurchase = MlmDistEpointPurchasePeer::doSelectOne($c);

        $bankId = 1;
        if ($distPackagePurchase) {
            $this->purchaseId = $distPackagePurchase->getPurchaseId();
            $this->amount = $distPackagePurchase->getAmount();
            $this->paymentReference = $distPackagePurchase->getPaymentReference();
            $bankId = $distPackagePurchase->getBankId();
        }
        $this->tradingCurrencyOnMT4 = "USD";
        if ($bankId == 2) {
            $this->bankName = $this->getAppSetting(Globals::SETTING_BANK_NAME_2);
            $this->bankSwiftCode = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE_2);
            $this->iban = $this->getAppSetting(Globals::SETTING_IBAN_2);
            $this->bankAccountHolder = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER_2);
            $this->bankAccountNumber = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER_2);
            $this->cityOfBank = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK_2);
            $this->countryOfBank = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK_2);
        } else {
            $this->bankName = $this->getAppSetting(Globals::SETTING_BANK_NAME);
            $this->bankSwiftCode = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE);
            $this->iban = $this->getAppSetting(Globals::SETTING_IBAN);
            $this->bankAccountHolder = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER);
            $this->bankAccountNumber = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER);
            $this->cityOfBank = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK);
            $this->countryOfBank = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK);
        }

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
    }

    public function executeIndex()
    {
        return $this->redirect('/member/summary');
    }

    public function executePackagePurchaseViaBankTransfer()
    {
        $c = new Criteria();
        $c->addDescendingOrderByColumn(MlmPackagePeer::PRICE);
        $packages = MlmPackagePeer::doSelect($c);

        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);
        $this->packages = $packages;
        $this->distDB = $distDB;

        if ($this->getRequestParameter('packageTypeId') != "" && $this->getRequest()->getFileName('bankSlip') != '') {
            $packageDB = MlmPackagePeer::retrieveByPk($this->getRequestParameter('packageTypeId'));
            $this->forward404Unless($packageDB);

            $uploadedFilename = $this->getRequest()->getFileName('bankSlip');
            $ext = explode(".", $this->getRequest()->getFileName('bankSlip'));
            $extensionName = $ext[count($ext) - 1];

            $filename = date("Ymd") . "_" . $distDB->getDistributorCode() . "_" . rand(1000, 9999) . "." . $extensionName;
            $this->getRequest()->moveFile('bankSlip', sfConfig::get('sf_upload_dir') . '/bankslip/' . $filename);

            $mlmDistPackagePurchase = new MlmDistPackagePurchase();
            $mlmDistPackagePurchase->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $mlmDistPackagePurchase->setRankId($packageDB->getPackageId());
            $mlmDistPackagePurchase->setRankCode($packageDB->getPackageName());
            //$mlmDistPackagePurchase->setInitRankId($packageDB->getPackageId());
            //$mlmDistPackagePurchase->setInitRankCode($packageDB->getPackageName());
            $mlmDistPackagePurchase->setAmount($packageDB->getPrice());
            $mlmDistPackagePurchase->setTransactionType(Globals::PURCHASE_PACKAGE_BANK_TRANSFER);
            $mlmDistPackagePurchase->setImageSrc($_SERVER['HTTP_HOST'] . "/uploads/bankslip/" . $filename);
            $mlmDistPackagePurchase->setStatusCode(Globals::STATUS_PENDING);
            //$mlmDistPackagePurchase->setRemarks($this->getRequestParameter('remarks'));
            $mlmDistPackagePurchase->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlmDistPackagePurchase->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

            $mlmDistPackagePurchase->save();

            $distDB->setStatusCode(Globals::STATUS_PAYMENT_PENDING);
            $distDB->save();
            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your requests has been submitted."));
            return $this->redirect('/member/summary');
        }
    }

    public function executeEpointPurchase()
    {
        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);
        $this->distDB = $distDB;

        $this->tradingCurrencyOnMT4 = "USD";
        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);

        $this->bankName = $this->getAppSetting(Globals::SETTING_BANK_NAME);
        $this->bankSwiftCode = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE);
        $this->iban = $this->getAppSetting(Globals::SETTING_IBAN);
        $this->bankAccountHolder = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER);
        $this->bankAccountNumber = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER);
        $this->cityOfBank = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK);
        $this->countryOfBank = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK);

        $this->bankName2 = $this->getAppSetting(Globals::SETTING_BANK_NAME_2);
        $this->bankSwiftCode2 = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE_2);
        $this->iban2 = $this->getAppSetting(Globals::SETTING_IBAN_2);
        $this->bankAccountHolder2 = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER_2);
        $this->bankAccountNumber2 = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER_2);
        $this->cityOfBank2 = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK_2);
        $this->countryOfBank2 = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK_2);

        if ($this->getRequestParameter('epointAmount') != "") {
            $amount = $this->getRequestParameter('epointAmount');
            $paymentReference = $this->generatePaymentReference();

            $mlmDistEpointPurchase = new MlmDistEpointPurchase();
            $mlmDistEpointPurchase->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $mlmDistEpointPurchase->setAmount($amount);
            $mlmDistEpointPurchase->setPaymentReference($paymentReference);
            $mlmDistEpointPurchase->setTransactionType(Globals::PURCHASE_EPOINT_BANK_TRANSFER);
            $mlmDistEpointPurchase->setStatusCode(Globals::STATUS_PENDING);
            $mlmDistEpointPurchase->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlmDistEpointPurchase->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

            $mlmDistEpointPurchase->save();

            $mlmDistEpointPurchase->setPaymentReference($mlmDistEpointPurchase->getPurchaseId());
            $mlmDistEpointPurchase->save();

            $paymentReference = $mlmDistEpointPurchase->getPaymentReference();

            $this->setFlash('purchaseId', $mlmDistEpointPurchase->getPurchaseId());
            $this->setFlash('amount', $amount);
            $this->setFlash('paymentReference', $paymentReference);
            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your requests has been submitted."));
            //$this->setFlash('successMsg', "Your requests has been submitted, to complete the funding, please proceed to remit the payment to the account, with details as indicated below:");
            return $this->redirect('/member/epointPurchase');
        }
    }

    public function executeDoUploadFile()
    {
        if ($this->getRequest()->getFileName('bankPassBook') != '') {
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $this->forward404Unless($distDB);

            $uploadedFilename = $this->getRequest()->getFileName('bankPassBook');
            $ext = explode(".", $this->getRequest()->getFileName('bankPassBook'));
            $extensionName = $ext[count($ext) - 1];

            $filename = "bankPassBook_" . date("Ymd") . "_" . $distDB->getDistributorCode() . "_" . rand(1000, 9999) . "." . $extensionName;
            $this->getRequest()->moveFile('bankPassBook', sfConfig::get('sf_upload_dir') . '/bank_pass_book/' . $filename);

            $distDB->setFileBankPassBook($filename);
            $distDB->save();

            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Upload successful."));
        }
        if ($this->getRequest()->getFileName('proofOfResidence') != '') {
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $this->forward404Unless($distDB);

            $uploadedFilename = $this->getRequest()->getFileName('proofOfResidence');
            $ext = explode(".", $this->getRequest()->getFileName('proofOfResidence'));
            $extensionName = $ext[count($ext) - 1];

            $filename = "proofOfResidence_" . date("Ymd") . "_" . $distDB->getDistributorCode() . "_" . rand(1000, 9999) . "." . $extensionName;
            $this->getRequest()->moveFile('proofOfResidence', sfConfig::get('sf_upload_dir') . '/proof_of_residence/' . $filename);

            $distDB->setFileProofOfResidence($filename);
            $distDB->save();

            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Upload successful."));
        }
        if ($this->getRequest()->getFileName('nric') != '') {
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $this->forward404Unless($distDB);

            $uploadedFilename = $this->getRequest()->getFileName('nric');
            $ext = explode(".", $this->getRequest()->getFileName('nric'));
            $extensionName = $ext[count($ext) - 1];

            $filename = "nric_" . date("Ymd") . "_" . $distDB->getDistributorCode() . "_" . rand(1000, 9999) . "." . $extensionName;
            $this->getRequest()->moveFile('nric', sfConfig::get('sf_upload_dir') . '/nric/' . $filename);

            $distDB->setFileNric($filename);
            $distDB->save();

            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Upload successful."));
        }
        return $this->redirect('/member/viewProfile');
    }

    public function executeUploadBankReceipt()
    {
        if ($this->getRequestParameter('purchaseId') != "" && $this->getRequest()->getFileName('bankSlip') != '') {
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $this->forward404Unless($distDB);
            $this->distDB = $distDB;

            $uploadedFilename = $this->getRequest()->getFileName('bankSlip');
            $ext = explode(".", $this->getRequest()->getFileName('bankSlip'));
            $extensionName = $ext[count($ext) - 1];

            $filename = date("Ymd") . "_" . $distDB->getDistributorCode() . "_" . rand(1000, 9999) . "." . $extensionName;
            $this->getRequest()->moveFile('bankSlip', sfConfig::get('sf_upload_dir') . '/bankslip/' . $filename);

            $mlmDistEpointPurchase = MlmDistEpointPurchasePeer::retrieveByPK($this->getRequestParameter('purchaseId'));
            $mlmDistEpointPurchase->setImageSrc($filename);
            //$mlmDistEpointPurchase->setImageSrc("http://" . $_SERVER['HTTP_HOST'] . "/uploads/bankslip/" . $filename);
            $mlmDistEpointPurchase->setDepositRemark($this->getRequestParameter('depositRemark'));
            $mlmDistEpointPurchase->setBankId($this->getRequestParameter('bankId'));
            $mlmDistEpointPurchase->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

            $mlmDistEpointPurchase->save();

            $this->setFlash('banksuccessMsg', $this->getContext()->getI18N()->__("Bank receipt upload successful."));
            return $this->redirect('/member/epointPurchase');
        }
    }

    public function executeUpdateTermCondition()
    {
        $mlm_distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($mlm_distributor);

        $mlm_distributor->setTermCondition(Globals::YES);
        $mlm_distributor->save();
        return $this->redirect('/member/summary');
    }

    public function executeRegister()
    {
        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2));
        // Concatenate the random string onto the random numbers
        // The font 'Anorexia' doesn't have a character for '8', so the numbers will only go up to 7
        // '0' is left out to avoid confusion with 'O'

        $str = rand(1, 7) . rand(1, 7) . $char;
        $this->getUser()->setAttribute(Globals::SYSTEM_CAPTCHA_ID, $str);
    }

    public function executeMemberRegistration()
    {
        $distDB = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        if ($distDB->getRankId() < 1) {
            return $this->redirect('/member/summary');
        }

        $c = new Criteria();
        //$c->add(MlmPackagePeer::PUBLIC_PURCHASE, 1);
        $c->add(MlmPackagePeer::PACKAGE_ID, 1);
        $packageDBs = MlmPackagePeer::doSelect($c);

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ecashAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->packageDBs = $packageDBs;
    }

    public function executeMemberRegistration2()
    {
        //if ($this->getRequestParameter('transactionPassword') <> "" && $this->getRequestParameter('pid') <> "") {
        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        if ($this->getRequestParameter('pid') <> "") {
            /*$tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));
            if ($tbl_user->getUserpassword2() <> $this->getRequestParameter('transactionPassword')) {
                $this->setFlash('errorMsg', "Invalid Security password");
                return $this->redirect('/member/memberRegistration');
            }*/

            $ledgerEPointBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
            $selectedPackage = MlmPackagePeer::retrieveByPK($this->getRequestParameter('pid'));
            $this->forward404Unless($selectedPackage);

            $amountNeeded = $selectedPackage->getPrice();

            /*if ($selectedPackage->getPackageId() == Globals::MAX_PACKAGE_ID) {
                $amountNeeded = $this->getRequestParameter('specialPackagePrice');
            }*/

            if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {

            } else {
                if ($amountNeeded > $ledgerEPointBalance) {
                    $this->setFlash('errorMsg', "In-sufficient e-Point amount");
                    return $this->redirect('/member/memberRegistration');
                }
            }
            $this->selectedPackage = $selectedPackage;
            $this->amountNeeded = $amountNeeded;
            $this->productCode = $this->getRequestParameter('productCode');

            $mlm_distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $this->distributor = $mlm_distributor;
            $this->sponsorId = $mlm_distributor->getDistributorCode();
            $this->sponsorName = $mlm_distributor->getFullName();
        } else {
            return $this->redirect('/member/memberRegistration');
        }
    }

    public function executeRegisterInfo()
    {
        if (!$this->getUser()->hasAttribute(Globals::SESSION_USERNAME)) {
            return $this->redirect('/member/register');
        }
    }

    public function executeUpdateProfile()
    {
        $mlm_distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($mlm_distributor);

        //$mlm_distributor->setNickname($this->getRequestParameter('nickName'));
        //$mlm_distributor->setFullName($this->getRequestParameter('fullname'));
        $mlm_distributor->setIc($this->getRequestParameter('ic'));
        if ($this->getRequestParameter('country') == 'China') {
            $mlm_distributor->setCountry('China (PRC)');
        } else {
            $mlm_distributor->setCountry($this->getRequestParameter('country'));
        }
        $mlm_distributor->setAddress($this->getRequestParameter('address'));
        $mlm_distributor->setAddress2($this->getRequestParameter('address2'));
        $mlm_distributor->setCity($this->getRequestParameter('city'));
        $mlm_distributor->setState($this->getRequestParameter('state'));
        $mlm_distributor->setPostcode($this->getRequestParameter('zip'));
        $mlm_distributor->setEmail($this->getRequestParameter('email'));
        $mlm_distributor->setAlternateEmail($this->getRequestParameter('alt_email'));
        $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
        $mlm_distributor->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $mlm_distributor->setDob("$y-$m-$d");
        }
        //$mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        //$mlm_distributor->setBankAccNo($this->getRequestParameter('bankNo'));
        //$mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolder'));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Profile update successfully"));

        return $this->redirect('/member/viewProfile');
    }

    public function executeUpdateBankInformation()
    {
        $mlm_distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($mlm_distributor);

        $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccNo'));
        $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));
        $mlm_distributor->setBankSwiftCode($this->getRequestParameter('bankSwiftCode'));
        $mlm_distributor->setVisaDebitCard($this->getRequestParameter('visaDebitCard'));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Bank Account Information update successfully"));

        //return $this->redirect('/member/viewBankInformation');
        return $this->redirect('/member/viewProfile');
    }

    public function executeDoRegister()
    {
        require_once('recaptchalib.php');
        $privatekey = "6LfhJtYSAAAAALocUxn6PpgfoWCFjRquNFOSRFdb";
        $resp = recaptcha_check_answer($privatekey,
                                       $_SERVER["REMOTE_ADDR"],
                                       $_POST["recaptcha_challenge_field"],
                                       $_POST["recaptcha_response_field"]);

        if (!$resp->is_valid) {
            $this->setFlash('errorMsg', "The CAPTCHA wasn't entered correctly. Go back and try it again.");
            return $this->redirect('home/login');
        }

        //$fcode = $this->generateFcode($this->getRequestParameter('country'));
        $fcode = $this->getRequestParameter('userName');
        $password = $this->getRequestParameter('userpassword');

        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $fcode);
        $exist = AppUserPeer::doSelectOne($c);
        //$this->forward404Unless(!$exist);
        $parentId = $this->getDistributorIdByCode($this->getRequestParameter('sponsorId'));
        $this->forward404Unless($parentId <> 0);

        //******************* upline distributor ID
        $uplineDistDB = $this->getDistributorInformation($this->getRequestParameter('sponsorId'));
        $this->forward404Unless($uplineDistDB);

        $treeStructure = $uplineDistDB->getTreeStructure() . "|" . $fcode . "|";
        $treeLevel = $uplineDistDB->getTreeLevel() + 1;

        $app_user = new AppUser();
        $app_user->setUsername($fcode);
        $app_user->setKeepPassword($password);
        $app_user->setUserpassword($password);
        $app_user->setKeepPassword2($password);
        $app_user->setUserpassword2($password);
        $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
        $app_user->setStatusCode(Globals::STATUS_PENDING);
        $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->save();

        // ****************************
        $mlm_distributor = new MlmDistributor();
        $mlm_distributor->setDistributorCode($fcode);
        $mlm_distributor->setUserId($app_user->getUserId());
        $mlm_distributor->setStatusCode(Globals::STATUS_PENDING);
        $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
        $mlm_distributor->setNickname($fcode);
        $mlm_distributor->setIc($this->getRequestParameter('ic'));
        if ($this->getRequestParameter('country') == 'China') {
            $mlm_distributor->setCountry('China (PRC)');
        } else {
            $mlm_distributor->setCountry($this->getRequestParameter('country'));
        }
        $mlm_distributor->setAddress($this->getRequestParameter('address'));
        $mlm_distributor->setAddress2($this->getRequestParameter('address2'));
        $mlm_distributor->setCity($this->getRequestParameter('city'));
        $mlm_distributor->setState($this->getRequestParameter('state'));
        $mlm_distributor->setPostcode($this->getRequestParameter('zip'));
        $mlm_distributor->setEmail($this->getRequestParameter('email'));
        $mlm_distributor->setAlternateEmail($this->getRequestParameter('alt_email'));
        $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
        $mlm_distributor->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $mlm_distributor->setDob("$y-$m-$d");
        }
        $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccountNo'));
        $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));

        $mlm_distributor->setTreeLevel($treeLevel);
        $mlm_distributor->setTreeStructure($treeStructure);
        $mlm_distributor->setUplineDistId($uplineDistDB->getDistributorId());
        $mlm_distributor->setUplineDistCode($uplineDistDB->getDistributorCode());

        $mlm_distributor->setSignName($this->getRequestParameter('sign_name'));
        $mlm_distributor->setSignDate(date("Y/m/d h:i:s A"));
        $mlm_distributor->setTermCondition($this->getRequestParameter('term_condition'));
        $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $fcode);

        /****************************/
        /*****  Send email **********/
        /****************************/
        /*error_reporting(E_STRICT);

        date_default_timezone_set(date_default_timezone_get());

        include_once('class.phpmailer.php');

        $subject = $this->getContext()->getI18N()->__("Vital Universe Group Registration email notification", null, 'email');
        $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $mlm_distributor->getNickname()), 'email') . ",<p><p>

        <p>" . $this->getContext()->getI18N()->__("Your registration request has been successfully sent to Vital Universe Group", null, 'email') . "</p>
        <p><b>" . $this->getContext()->getI18N()->__("Trader ID", null) . ": " . $fcode . "</b>
        <p><b>" . $this->getContext()->getI18N()->__("Password", null) . ": " . $password . "</b>";

        $mail = new PHPMailer();
        $mail->IsMail(); // telling the class to use SMTP
        $mail->Host = Mails::EMAIL_HOST; // SMTP server
        $mail->Sender = Mails::EMAIL_FROM_NOREPLY;
        $mail->From = Mails::EMAIL_FROM_NOREPLY;
        $mail->FromName = Mails::EMAIL_FROM_NOREPLY_NAME;
        $mail->Subject = $subject;
        $mail->CharSet="utf-8";

        $text_body = $body;

        $mail->Body = $body;
        $mail->AltBody = $text_body;
        $mail->AddAddress($mlm_distributor->getEmail(), $mlm_distributor->getNickname());
        $mail->AddBCC("r9projecthost@gmail.com", "jason");

        if (!$mail->Send()) {
            echo $mail->ErrorInfo;
        }*/
        return $this->redirect('/member/registerInfo');
    }

    public function executeDoMemberRegistration()
    {
        $userName = $this->getRequestParameter('userName', '');
        //$fcode = $this->generateFcode($this->getRequestParameter('country'));
        $fcode = $userName;
        $password = $this->getRequestParameter('userpassword');
        $password2 = $this->getRequestParameter('securityPassword');
        $packageId = $this->getRequestParameter('packageId');
        $position = $this->getRequestParameter('position1');
        $amountNeeded = $this->getRequestParameter('amountNeeded');
        $doAction = $this->getRequestParameter('doAction', '');

        $cardNumber = $this->getRequestParameter('cardNumber', '');
        $cvvNumber = $this->getRequestParameter('cvvNumber', '');
        /* ****************************************************
         * get distributor last account ledger epoint balance
         * ***************************************************/
        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $userName);
        $exist = AppUserPeer::doSelectOne($c);

        if ($exist) {
            $this->setFlash('errorMsg', "User Name already exist.");
            return $this->redirect('/member/memberRegistration');
        }

        $c = new Criteria();
        $c->add(MlmMemberCardPeer::CARD_NUMBER, $cardNumber);
        $c->add(MlmMemberCardPeer::CVV_NUMBER, $cvvNumber);
        $c->add(MlmMemberCardPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existMemberCard = MlmMemberCardPeer::doSelectOne($c);

        if (!$existMemberCard) {
            $this->setFlash('errorMsg', "Invalid Card Number");
            return $this->redirect('/member/memberRegistration');
        }

        $packageDB = MlmPackagePeer::retrieveByPK($packageId);

        if (!$packageDB) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Action."));
            return $this->redirect('/member/memberRegistration');
        }

        $applicationPackageName = $packageDB->getPackageName();
        $packagePrice = $packageDB->getPrice();

        $sponsorAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);

        if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {

        } else {
            if ($packagePrice > $sponsorAccountBalance) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient fund to purchase package."));
                return $this->redirect('/member/memberRegistration');
            }
        }

        $con = Propel::getConnection(MlmDistributorPeer::DATABASE_NAME);
        try {
            $con->begin();
            //******************* upline distributor ID

            $app_user = new AppUser();
            $mlm_distributor = new MlmDistributor();
            $uplineDistDB = new MlmDistributor();
            $uplineDistId = 0;
            if ($doAction == "PENDING_MEMBER") {
                $app_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));
                $app_user->setStatusCode(Globals::STATUS_ACTIVE);
                $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->save();

                $userName = $app_user->getUsername();
                $password = $app_user->getUserpassword();
                $password2 = $app_user->getUserpassword2();
                $mlm_distributor = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));

                $uplineDistDB = MlmDistributorPeer::retrieveByPk($mlm_distributor->getUplineDistId());
                $uplineDistId = $uplineDistDB->getDistributorId();

                $mlm_distributor->setRankId($packageDB->getPackageId());
                $mlm_distributor->setRankCode($packageDB->getPackageName());
                $mlm_distributor->setInitRankId($packageDB->getPackageId());
                $mlm_distributor->setInitRankCode($packageDB->getPackageName());
                $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
                $mlm_distributor->setPackagePurchaseFlag("Y");
                $mlm_distributor->setActiveDatetime(date("Y/m/d h:i:s A"));
                $mlm_distributor->setActivatedBy($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->save();
            } else {
                $uplineDistCode = $this->getRequestParameter('sponsorId');

                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $uplineDistCode);
                $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%" . $this->getUser()->getAttribute(Globals::SESSION_DISTID) . "%", Criteria::LIKE);
                $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
                $uplineDistDB = MlmDistributorPeer::doSelectOne($c);

                if (!$uplineDistDB) {
                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Referrer ID."));
                    return $this->redirect('/member/memberRegistration');
                }

                $uplineDistId = $uplineDistDB->getDistributorId();
                $treeLevel = $uplineDistDB->getTreeLevel() + 1;


                $app_user->setUsername($userName);
                $app_user->setKeepPassword($password);
                $app_user->setUserpassword($password);
                $app_user->setKeepPassword2($password2);
                $app_user->setUserpassword2($password2);
                $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
                $app_user->setStatusCode(Globals::STATUS_ACTIVE);
                $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $app_user->save();


                $mlm_distributor->setDistributorCode($fcode);
                $mlm_distributor->setUserId($app_user->getUserId());
                $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
                $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
                $mlm_distributor->setNickname($userName);
                $mlm_distributor->setIc($this->getRequestParameter('ic'));
                if ($this->getRequestParameter('country') == 'China') {
                    $mlm_distributor->setCountry('China (PRC)');
                } else {
                    $mlm_distributor->setCountry($this->getRequestParameter('country'));
                }
                $mlm_distributor->setAddress($this->getRequestParameter('address'));
                $mlm_distributor->setAddress2($this->getRequestParameter('address2'));
                $mlm_distributor->setCity($this->getRequestParameter('city'));
                $mlm_distributor->setState($this->getRequestParameter('state'));
                $mlm_distributor->setPostcode($this->getRequestParameter('zip'));
                $mlm_distributor->setEmail($this->getRequestParameter('email'));
                $mlm_distributor->setAlternateEmail($this->getRequestParameter('alt_email'));
                $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
                $mlm_distributor->setGender($this->getRequestParameter('gender'));
                if ($this->getRequestParameter('dob')) {
                    list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
                    $mlm_distributor->setDob("$y-$m-$d");
                }
                $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
                $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccountNo'));
                $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));

                $mlm_distributor->setTreeLevel($treeLevel);
                $mlm_distributor->setUplineDistId($uplineDistDB->getDistributorId());
                $mlm_distributor->setUplineDistCode($uplineDistDB->getDistributorCode());

                $mlm_distributor->setSignName($this->getRequestParameter('sign_name'));
                $mlm_distributor->setSignDate(date("Y/m/d h:i:s A"));
                $mlm_distributor->setTermCondition($this->getRequestParameter('term_condition'));

                $mlm_distributor->setRankId($packageDB->getPackageId());
                $mlm_distributor->setRankCode($packageDB->getPackageName());
                $mlm_distributor->setInitRankId($packageDB->getPackageId());
                $mlm_distributor->setInitRankCode($packageDB->getPackageName());
                $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
                if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {
                    $mlm_distributor->setPackagePurchaseFlag("N");
                    $mlm_distributor->setRemark("loan account");
                    $mlm_distributor->setLoanAccount("Y");
                } else {
                    $mlm_distributor->setPackagePurchaseFlag("Y");
                }
                $mlm_distributor->setActiveDatetime(date("Y/m/d h:i:s A"));
                $mlm_distributor->setActivatedBy($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_distributor->save();

                $treeStructure = $uplineDistDB->getTreeStructure() . "|" . $mlm_distributor->getDistributorId() . "|";
                $mlm_distributor->setTreeStructure($treeStructure);
                $mlm_distributor->setMemberCardNo($cardNumber);
                $mlm_distributor->save();

                $existMemberCard->setStatusCode(Globals::STATUS_COMPLETE);
                $existMemberCard->save();
            }

            $sponsorId = $mlm_distributor->getDistributorId();
            /**************************************/
            /*  Direct REFERRAL Bonus For Upline
            /**************************************/
            $uplineDistPackage = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
            //$directSponsorPercentage = $uplineDistPackage->getDrbCommission();
            //$directSponsorBonusAmount = $directSponsorPercentage * $packagePrice / 100;
            $directSponsorBonusAmount = $packageDB->getDrbCommission();
            //$totalBonusPayOut = $directSponsorPercentage;

            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");

            /* ****************************************************
             * Update upline distributor account
             * ***************************************************/
            $sponsorAccountBalance = $sponsorAccountBalance - $packagePrice;
            if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {

            } else {
                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
                $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $packageDB->getPackageName() . ")");
                $mlm_account_ledger->setCredit(0);
                $mlm_account_ledger->setDebit($packagePrice);
                $mlm_account_ledger->setBalance($sponsorAccountBalance);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                /******************************/
                /*  Direct Sponsor Bonus
                /******************************/
                //while ($totalBonusPayOut <= Globals::TOTAL_BONUS_PAYOUT) {
                $distAccountEcashBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($uplineDistId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_DRB);
                $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $mlm_distributor->getDistributorCode() . " - " . $packageDB->getPackageName() . ")");
                $mlm_account_ledger->setCredit($directSponsorBonusAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $directSponsorBonusAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                /******************************/
                /*  Commission
                /******************************/
                $c = new Criteria();
                $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $uplineDistId);
                $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_DRB);
                $c->addDescendingOrderByColumn(MlmDistCommissionLedgerPeer::CREATED_ON);
                $sponsorDistCommissionLedgerDB = MlmDistCommissionLedgerPeer::doSelectOne($c);

                $dsbBalance = 0;
                if ($sponsorDistCommissionLedgerDB)
                    $dsbBalance = $sponsorDistCommissionLedgerDB->getBalance();

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($uplineDistId);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_DRB);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_REGISTER);
                $sponsorDistCommissionledger->setCredit($directSponsorBonusAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($dsbBalance + $directSponsorBonusAmount);
                $sponsorDistCommissionledger->setRemark("DRB FOR PACKAGE PURCHASE (" . $mlm_distributor->getDistributorCode() . " - " . $packageDB->getPackageName() . ")");
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();
            }

            $con->commit();

            /****************************/
            /*****  Send email **********/
            /****************************/
            $receiverEmail = $this->getRequestParameter('email', $mlm_distributor->getEmail());
            $receiverFullname = $this->getRequestParameter('fullname', $mlm_distributor->getFullName());
            $subject = "Ronuva - Thank You for Your Registration";

            $body = "<table width='100%' cellspacing='0' cellpadding='0' border='0' bgcolor='#939393' align='center'>
	<tbody>
		<tr>
			<td style='padding:20px 0px'>
				<table width='606' cellspacing='0' cellpadding='0' border='0' align='center' style='background:white;font-family:Arial,Helvetica,sans-serif'>
					<tbody>
						<tr>
							<td colspan='2'>
								<a target='_blank' href='http://www.ronuva.com'><img width='606' height='115' border='0' src='http://www.ronuva.com/images/email/banner.png' alt='Ronuva'></a></td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table border='0' cellspacing='0' cellpadding='0' style='width:440.0pt;border-collapse:collapse'>
                                        <tbody>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Member ID<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $userName . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Password<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $password . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Security Password<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $password2 . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Member ID<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $fcode . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Full Name(As In IC)<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $receiverFullname . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>

                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Email<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'><a
                                                        href='mailto:" . $this->getRequestParameter('email', $mlm_distributor->getEmail()) . "'
                                                        target='_blank'>" . $this->getRequestParameter('email', $mlm_distributor->getEmail()) . "</a><u></u><u></u></span></p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Mobile Number<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $this->getRequestParameter('contactNumber', $mlm_distributor->getContact()) . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Country<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $this->getRequestParameter('country', $mlm_distributor->getCountry()) . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>

                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Package<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $applicationPackageName . " (RM " . number_format($packagePrice, 2) . ")<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        </tbody>
                                    </table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td width='606' style='font-size:0;line-height:0' bgcolor='#0080C8'>
							<img src='http://www.ronuva.com/images/email/transparent.gif' height='1'>
							</td>
						</tr>
						<tr>
							<td width='606' style='font-size:0;line-height:0' colspan='2'>
								<img src='http://www.ronuva.com/images/email/transparent.gif' height='10'>
							</td>
						</tr>

						<tr>
							<td width='606' style='padding:15px 15px 0px;color:rgb(153,153,153);font-size:11px' colspan='2' align='right'>
							<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
								<em>
									Best Regards,<br>
									<strong>Ronuva Account Opening Team</strong><br>
								</em>
							</font>
							<br>
							<a href='http://www.ronuva.com' target='_blank'><img src='http://www.ronuva.com/images/email/logo.png' border='0'></a>
							<br>
						</tr>

						<tr>
							<td width='606' style='padding:5px 15px 20px;color:rgb(153,153,153);font-size:11px' colspan='2'>
							<p align='justify'>
								<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
									CONFIDENTIALITY: This e-mail and any files transmitted with it are confidential and intended solely for the use of the recipient(s) only. Any review, retransmission, dissemination or other use of, or taking any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you have received this e-mail in error please notify the sender immediately and destroy the material whether stored on a computer or otherwise.
								</font>
							</p>
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>";

            $sendMailService = new SendMailService();
            $sendMailService->sendMail($receiverEmail, $receiverFullname, $subject, $body);
        } catch (PropelException $e) {
            $con->rollback();
            throw $e;
        }

        if ($doAction == "PENDING_MEMBER") {
            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("(" . $fcode . ") Package Purchase Successfully."));
            return $this->redirect('/member/summary');
        } else {
            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Member (" . $fcode . ") Registered Successfully."));
            return $this->redirect('/member/memberRegistration');
        }
        return $this->redirect('/member/summary');
    }

    public function executeDoPackageUpgrade()
    {
        $userName = $this->getRequestParameter('userName', '');
        //$fcode = $this->generateFcode($this->getRequestParameter('country'));
        $fcode = $userName;
        $password = $this->getRequestParameter('userpassword');
        $password2 = $this->getRequestParameter('securityPassword');
        $packageId = $this->getRequestParameter('packageId');
        $doAction = $this->getRequestParameter('doAction', '');
        /* ****************************************************
         * get distributor last account ledger epoint balance
         * ***************************************************/
        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $userName);
        $exist = AppUserPeer::doSelectOne($c);

        if ($exist) {
            $this->setFlash('errorMsg', "User Name already exist.");
            return $this->redirect('/member/packageUpgrade');
        }

        $packageDB = MlmPackagePeer::retrieveByPK($packageId);

        if (!$packageDB) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Action."));
            return $this->redirect('/member/packageUpgrade');
        }

        $applicationPackageName = $packageDB->getPackageName();
        $packagePrice = $packageDB->getPrice();

        $sponsorAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);

        if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {

        } else {
            if ($packagePrice > $sponsorAccountBalance) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient fund to purchase package."));
                return $this->redirect('/member/packageUpgrade');
            }
        }

        $con = Propel::getConnection(MlmDistributorPeer::DATABASE_NAME);
        try {
            $con->begin();
            //******************* upline distributor ID
            $mlm_distributor = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));

            $uplineDistDB = MlmDistributorPeer::retrieveByPk($mlm_distributor->getUplineDistId());
            $uplineDistId = $uplineDistDB->getDistributorId();

            $mlm_distributor->setRankId($packageDB->getPackageId());
            $mlm_distributor->setRankCode($packageDB->getPackageName());
            $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_distributor->save();

            $sponsorId = $mlm_distributor->getDistributorId();
            /**************************************/
            /*  Direct REFERRAL Bonus For Upline
            /**************************************/
            $uplineDistPackage = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
            //$directSponsorPercentage = $uplineDistPackage->getDrbCommission();
            //$directSponsorBonusAmount = $directSponsorPercentage * $packagePrice / 100;
            $directSponsorBonusAmount = $packageDB->getDrbCommission();
            //$totalBonusPayOut = $directSponsorPercentage;

            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");

            /* ****************************************************
             * Update upline distributor account
             * ***************************************************/
            $sponsorAccountBalance = $sponsorAccountBalance - $packagePrice;
            if ($this->getUser()->getAttribute(Globals::SESSION_MASTER_LOGIN) == Globals::TRUE && $this->getUser()->getAttribute(Globals::SESSION_DISTID) == Globals::LOAN_ACCOUNT_CREATOR_DIST_ID) {

            } else {
                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
                $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $packageDB->getPackageName() . ")");
                $mlm_account_ledger->setCredit(0);
                $mlm_account_ledger->setDebit($packagePrice);
                $mlm_account_ledger->setBalance($sponsorAccountBalance);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                /******************************/
                /*  Direct Sponsor Bonus
                /******************************/
                //while ($totalBonusPayOut <= Globals::TOTAL_BONUS_PAYOUT) {
                $distAccountEcashBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($uplineDistId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_DRB);
                $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $mlm_distributor->getDistributorCode() . " - " . $packageDB->getPackageName() . ")");
                $mlm_account_ledger->setCredit($directSponsorBonusAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $directSponsorBonusAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                /******************************/
                /*  Commission
                /******************************/
                $c = new Criteria();
                $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $uplineDistId);
                $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_DRB);
                $c->addDescendingOrderByColumn(MlmDistCommissionLedgerPeer::CREATED_ON);
                $sponsorDistCommissionLedgerDB = MlmDistCommissionLedgerPeer::doSelectOne($c);

                $dsbBalance = 0;
                if ($sponsorDistCommissionLedgerDB)
                    $dsbBalance = $sponsorDistCommissionLedgerDB->getBalance();

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($uplineDistId);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_DRB);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_REGISTER);
                $sponsorDistCommissionledger->setCredit($directSponsorBonusAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($dsbBalance + $directSponsorBonusAmount);
                $sponsorDistCommissionledger->setRemark("DRB FOR PACKAGE PURCHASE (" . $mlm_distributor->getDistributorCode() . " - " . $packageDB->getPackageName() . ")");
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();
            }

            $con->commit();

            /****************************/
            /*****  Send email **********/
            /****************************/
            $receiverEmail = $this->getRequestParameter('email', $mlm_distributor->getEmail());
            $receiverFullname = $this->getRequestParameter('fullname', $mlm_distributor->getFullName());
            $subject = "Ronuva - Thank You for Your Registration";

            $body = "<table width='100%' cellspacing='0' cellpadding='0' border='0' bgcolor='#939393' align='center'>
	<tbody>
		<tr>
			<td style='padding:20px 0px'>
				<table width='606' cellspacing='0' cellpadding='0' border='0' align='center' style='background:white;font-family:Arial,Helvetica,sans-serif'>
					<tbody>
						<tr>
							<td colspan='2'>
								<a target='_blank' href='http://www.ronuva.com'><img width='606' height='115' border='0' src='http://www.ronuva.com/images/email/banner.png' alt='Ronuva'></a></td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table border='0' cellspacing='0' cellpadding='0' style='width:440.0pt;border-collapse:collapse'>
                                        <tbody>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Member ID<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $userName . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Password<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $password . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Security Password<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $password2 . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180' style='width:135.0pt;border:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Member ID<u></u><u></u></span>
                                                </p></td>
                                            <td style='border:solid black 1.0pt;border-left:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'><p
                                                    class='MsoNormal'><span
                                                    style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $fcode . "<u></u><u></u></span>
                                            </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Full Name(As In IC)<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $receiverFullname . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>

                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Email<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'><a
                                                        href='mailto:" . $this->getRequestParameter('email', $mlm_distributor->getEmail()) . "'
                                                        target='_blank'>" . $this->getRequestParameter('email', $mlm_distributor->getEmail()) . "</a><u></u><u></u></span></p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Mobile Number<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $this->getRequestParameter('contactNumber', $mlm_distributor->getContact()) . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Country<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $this->getRequestParameter('country', $mlm_distributor->getCountry()) . "<u></u><u></u></span>
                                                </p></td>
                                        </tr>

                                        <tr>
                                            <td width='180'
                                                style='width:135.0pt;border:solid black 1.0pt;border-top:none;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>Package<u></u><u></u></span>
                                                </p></td>
                                            <td style='border-top:none;border-left:none;border-bottom:solid black 1.0pt;border-right:solid black 1.0pt;padding:2.25pt 2.25pt 2.25pt 2.25pt'>
                                                <p class='MsoNormal'><span
                                                        style='font-size:8.5pt;font-family:&quot;Verdana&quot;,&quot;sans-serif&quot;'>" . $applicationPackageName . " (RM " . number_format($packagePrice, 2) . ")<u></u><u></u></span>
                                                </p></td>
                                        </tr>
                                        </tbody>
                                    </table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td width='606' style='font-size:0;line-height:0' bgcolor='#0080C8'>
							<img src='http://www.ronuva.com/images/email/transparent.gif' height='1'>
							</td>
						</tr>
						<tr>
							<td width='606' style='font-size:0;line-height:0' colspan='2'>
								<img src='http://www.ronuva.com/images/email/transparent.gif' height='10'>
							</td>
						</tr>

						<tr>
							<td width='606' style='padding:15px 15px 0px;color:rgb(153,153,153);font-size:11px' colspan='2' align='right'>
							<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
								<em>
									Best Regards,<br>
									<strong>Ronuva Account Opening Team</strong><br>
								</em>
							</font>
							<br>
							<a href='http://www.ronuva.com' target='_blank'><img src='http://www.ronuva.com/images/email/logo.png' border='0'></a>
							<br>
						</tr>

						<tr>
							<td width='606' style='padding:5px 15px 20px;color:rgb(153,153,153);font-size:11px' colspan='2'>
							<p align='justify'>
								<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
									CONFIDENTIALITY: This e-mail and any files transmitted with it are confidential and intended solely for the use of the recipient(s) only. Any review, retransmission, dissemination or other use of, or taking any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you have received this e-mail in error please notify the sender immediately and destroy the material whether stored on a computer or otherwise.
								</font>
							</p>
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>";

            $sendMailService = new SendMailService();
            $sendMailService->sendMail($receiverEmail, $receiverFullname, $subject, $body);
        } catch (PropelException $e) {
            $con->rollback();
            throw $e;
        }

        return $this->redirect('/member/summary');
    }

    // **********************************************************************************************
    // *****************************         For broker registeration          **********************
    // **********************************************************************************************
    function generateFcode()
    {
        $max_digit = 999999999;
        $digit = 9;

        while (true) {
            $fcode = rand(0, $max_digit) . "";
            $fcode = str_pad($fcode, $digit, "0", STR_PAD_LEFT);

            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $fcode);
            $existDist = MlmDistributorPeer::doSelectOne($c);

            if (!$existDist) {
                break;
            }
        }
        return $fcode;
    }

    public function executeOpenDemoAccount()
    {
        $error = false;
        $errorMsg = "";

        //_wpcf7	1264
        //_wpcf7_is_ajax_call	1
        //_wpcf7_unit_tag	wpcf7-f1264-p587-o1
        //_wpcf7_version	3.3.1
        //_wpnonce	f24ca11af2
        //countrylist	Angola
        //f-name	firstname
        //l-name	last name
        //phone-number	phonr
        //title	Mrs
        //your-email	test@asdff
        if (!$this->getRequestParameter('your-email')) {
            $error = true;
            $errorMsg = "Email is required.";
        } else if (!$this->getRequestParameter('f-name')) {
            $error = true;
            $errorMsg = "First Name is required.";
        } else {
            $mlm_mt4_demo_request = new MlmMt4DemoRequest();
            $mlm_mt4_demo_request->setFirstName($this->getRequestParameter('f-name'));
            $mlm_mt4_demo_request->setEmail($this->getRequestParameter('your-email'));
            $mlm_mt4_demo_request->setStatusCode(Globals::STATUS_ACTIVE);
            $mlm_mt4_demo_request->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_mt4_demo_request->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_mt4_demo_request->setCountry($this->getRequestParameter('countrylist'));
            $mlm_mt4_demo_request->setPhoneNumber($this->getRequestParameter('phone-number'));
            $mlm_mt4_demo_request->setLastName($this->getRequestParameter('l-name'));
            $mlm_mt4_demo_request->setTitle($this->getRequestParameter('title'));
            $mlm_mt4_demo_request->setLiveDemo("DEMO");
            $mlm_mt4_demo_request->setAddress1($this->getRequestParameter('address-1'));
            $mlm_mt4_demo_request->setAddress2($this->getRequestParameter('address-2'));
            $mlm_mt4_demo_request->setAddressState($this->getRequestParameter('state'));
            $mlm_mt4_demo_request->setAgreeOfBusiness($this->getRequestParameter('agreeofBusiness'));
            $mlm_mt4_demo_request->setRiskDisclosure($this->getRequestParameter('agreeofRiskDisclosure'));
            $mlm_mt4_demo_request->setCountryOfCitizen($this->getRequestParameter('coutrylist'));
            $mlm_mt4_demo_request->setCity($this->getRequestParameter('city'));
            $mlm_mt4_demo_request->setDobDay($this->getRequestParameter('menu-dob-day'));
            $mlm_mt4_demo_request->setDobMonth($this->getRequestParameter('menu-dob-month'));
            $mlm_mt4_demo_request->setDobYear($this->getRequestParameter('menu-dob-year'));
            $mlm_mt4_demo_request->setRefId($this->getRequestParameter('referid'));
            $mlm_mt4_demo_request->setPassport($this->getRequestParameter('ssnumber'));
            $mlm_mt4_demo_request->setSubject($this->getRequestParameter('your-subject'));

            $mlm_mt4_demo_request->save();

            $subject = "Thank you for register RONUVA Demo Account 感谢您申请博马思金融交易模拟帐户";
            //$subject = "Thank you for register RONUVA Demo Account";

            $body = "<table width='100%' cellspacing='0' cellpadding='0' border='0' bgcolor='#939393' align='center'>
	<tbody>
		<tr>
			<td style='padding:20px 0px'>
				<table width='606' cellspacing='0' cellpadding='0' border='0' align='center' style='background:white;font-family:Arial,Helvetica,sans-serif'>
					<tbody>
						<tr>
							<td colspan='2'>
								<a target='_blank' href='http://www.ronuva.com'><img width='606' height='115' border='0' src='http://partner.ronuva.com/images/email/banner.png' alt='RONUVA'></a></td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table style='background-color:rgb(246,246,246)'>
													<tbody>
														<tr>
															<td valign='top' style='padding-top:15px;padding-left:10px'>
																<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:14px;line-height:17px'>
																	Dear <strong>" . $this->getRequestParameter("l-name") . " " . $this->getRequestParameter("f-name") . "</strong>,<br><br>
																	Thank you for your interest in opening a Free Demo Account with RONUVA. We are proud to offer our cutting-edge trading platform with industry leading performance and stability. Test your market strategies and get used to our platform before starting for real.
                                                                    <br><br>
                                                                    Kindly download the MT4 in order to start your trading activities.
																</font>
																<br>
																<br>
																<br>
																<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:17px'>
																Forex, spread bets and CFDs are leveraged products. They may not be suitable for you as they carry a high degree of risk to your capital and you can lose more than your initial investment. You should ensure you understand all of the risks.
																</font>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>
						<tr>
							<td style='padding:5px 15px 15px;font-weight:bold' colspan='2'>
								<table width='100%' cellpadding='0' cellspacing='0' border='0'>
									<tbody>
									<tr style='text-align:center;line-height:15px'>
										<td style='font-size:0;line-height:0' align='right'><img src='http://partner.ronuva.com/images/email/img-platform.gif' width='85' height='60'></td>
									</tr>
									<tr>
										<td style='line-height:15px' align='right'>
											<font face='Arial, Verdana, sans-serif' size='3' color='#58584b' style='font-size:11px;line-height:15px'>
												<strong>RONUVA<br>MT4 Terminal</strong>
											</font>
										</td>
									</tr>
									<tr><td style='line-height:15px' align='right'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'></td></tr>
									<tr>
										<td style='line-height:15px' align='right'><a href='http://partner.ronuva.com/download/demoMt4' target='_blank'><img src='http://partner.ronuva.com/images/email/btn-download.png' height='26' width='85' border='0'></a></td>
									</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table style='background-color:rgb(246,246,246)'>
													<tbody>
														<tr>
															<td valign='top' style='padding-top:15px;padding-left:10px'>
																<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:14px;line-height:17px'>
																	亲爱的 <STRONG>" . $this->getRequestParameter('l-name') . " " . $this->getRequestParameter('f-name') . "</strong>，<br><br>
																	你的免费模拟帐户将使你可以进行“纸上贸易”，我们很自豪能够提供最先进的交易平台，提供业界领先的性能和稳定性，使用MetaTrader 4可以允许你开发和测试您的交易策略。

																	<br><br>如想立刻体验交易，请下载并安装MT4。
																	<br>
																</font>
																<br>
																<br>
																<br>
																<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:17px'>
																买外汇或者期货都是一种杠杆投资。他们可能不适合您，因为他们具有很高的风险，您可能会失去您最初的投资资金，所以您必须确保你了解所有的风险。
																</font>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>
						<tr>
							<td style='padding:5px 15px 15px;font-weight:bold' colspan='2'>
								<table width='100%' cellpadding='0' cellspacing='0' border='0'>
									<tbody>
									<tr style='text-align:center;line-height:15px'>
										<td style='font-size:0;line-height:0' align='right'><img src='http://partner.ronuva.com/images/email/img-platform.gif' width='85' height='60'></td>
									</tr>
									<tr>
										<td style='line-height:15px' align='right'>
											<font face='Arial, Verdana, sans-serif' size='3' color='#58584b' style='font-size:11px;line-height:15px'>
												<strong>RONUVA<br>MT4 Terminal</strong>
											</font>
										</td>
									</tr>
									<tr><td style='line-height:15px' align='right'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'></td></tr>
									<tr>
										<td style='line-height:15px' align='right'><a href='http://partner.ronuva.com/download/demoMt4' target='_blank'><img src='http://partner.ronuva.com/images/email/btn-download_cn.png' height='26' width='85' border='0'></a></td>
									</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td width='606' style='font-size:0;line-height:0' bgcolor='#0080C8'>
							<img src='http://partner.ronuva.com/images/email/transparent.gif' height='1'>
							</td>
						</tr>
						<tr>
							<td width='606' style='font-size:0;line-height:0' colspan='2'>
								<img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'>
							</td>
						</tr>

						<tr>
							<td width='606' style='padding:15px 15px 0px;color:rgb(153,153,153);font-size:11px' colspan='2' align='right'>
							<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
								<em>
									Best Regards,<br>
									<strong>RONUVA</strong><br>
									E mail : admin@ronuva.com
								</em>
							</font>
							<br>
							<a href='http://ronuva.com/' target='_blank'><img src='http://partner.ronuva.com/images/email/logo.png' width='254' height='87' border='0'></a>
							<br>
						</tr>

						<tr>
							<td width='606' style='padding:5px 15px 20px;color:rgb(153,153,153);font-size:11px' colspan='2'>
							<p align='justify'>
								<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
									RONUVA is managed by RONUVA Capital Limited which is authorised and regulated in the New Zealand by the Financial Services Provider. FSP Register number is 252705. Registered Office: Level 8, 10/12 Scotia Place, Suite 11, Auckland City Centre, Auckland, 1010, New Zealand. Tel (+64) 93791159, Email accounts@ronuva.com
									<br><br>RONUVA Capital Limited is a subsidiary of Royale Group Holding Inc. a public listed company in USA.
									<br><br>CONFIDENTIALITY: This e-mail and any files transmitted with it are confidential and intended solely for the use of the recipient(s) only. Any review, retransmission, dissemination or other use of, or taking any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you have received this e-mail in error please notify the sender immediately and destroy the material whether stored on a computer or otherwise.
									<br><br>DISCLAIMER: Any views or opinions presented within this e-mail are solely those of the author and do not necessarily represent those of RONUVA capital Limited, unless otherwise specifically stated. The content of this message does not constitute Investment Advice.
									<br><br>RISK WARNING: Forex, spread bets, and CFDs carry a high degree of risk to your capital and it is possible to lose more than your initial investment. Only speculate with money you can afford to lose. As with any trading, you should not engage in it unless you understand the nature of the transaction you are entering into and, the true extent of your exposure to the risk of loss. These products may not be suitable for all investors, therefore if you do not fully understand the risks involved, please seek independent advice.
								</font>
							</p>
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>";

            //$sendMailService = new SendMailService();
            //$sendMailService->sendMail($this->getRequestParameter('your-email'), $this->getRequestParameter('l-name')." ".$this->getRequestParameter('f-name'), $subject, $body);
        }

        $arr = array(
            'error' => $error,
            'errorMsg' => $errorMsg
        );

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeOpenLiveAccount()
    {
        $error = false;
        $errorMsg = "";

        //_wpcf7	1266
        //_wpcf7_is_ajax_call	1
        //_wpcf7_unit_tag	wpcf7-f1266-p667-o1
        //_wpcf7_version	3.3.1
        //_wpnonce	5283ef444c
        //address-1	address
        //address-2	address 2
        //agreeofBusiness	1
        //agreeofRiskDisclosure	1
        //city	city
        //countrylist	Albania
        //coutrylist	Armenia
        //f-name	first name
        //l-name	last name
        //menu-dob-day	23
        //menu-dob-month	12
        //menu-dob-year	2000
        //phone-number	phone
        //referid	referral
        //ssnumber	password
        //state	state
        //title	Mr.
        //your-email	email
        //your-subject	subject

        if (!$this->getRequestParameter('your-email')) {
            $error = true;
            $errorMsg = "Email is required.";
        } else if (!$this->getRequestParameter('f-name')) {
            $error = true;
            $errorMsg = "First Name is required.";
        } else {
            $mlm_mt4_demo_request = new MlmMt4DemoRequest();
            $mlm_mt4_demo_request->setFirstName($this->getRequestParameter('f-name'));
            $mlm_mt4_demo_request->setEmail($this->getRequestParameter('your-email'));
            $mlm_mt4_demo_request->setStatusCode(Globals::STATUS_ACTIVE);
            $mlm_mt4_demo_request->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_mt4_demo_request->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_mt4_demo_request->setCountry($this->getRequestParameter('countrylist'));
            $mlm_mt4_demo_request->setPhoneNumber($this->getRequestParameter('phone-number'));
            $mlm_mt4_demo_request->setLastName($this->getRequestParameter('l-name'));
            $mlm_mt4_demo_request->setTitle($this->getRequestParameter('title'));
            $mlm_mt4_demo_request->setLiveDemo("LIVE");
            $mlm_mt4_demo_request->setAddress1($this->getRequestParameter('address-1'));
            $mlm_mt4_demo_request->setAddress2($this->getRequestParameter('address-2'));
            $mlm_mt4_demo_request->setAddressState($this->getRequestParameter('state'));
            $mlm_mt4_demo_request->setAgreeOfBusiness($this->getRequestParameter('agreeofBusiness'));
            $mlm_mt4_demo_request->setRiskDisclosure($this->getRequestParameter('agreeofRiskDisclosure'));
            $mlm_mt4_demo_request->setCountryOfCitizen($this->getRequestParameter('coutrylist'));
            $mlm_mt4_demo_request->setCity($this->getRequestParameter('city'));
            $mlm_mt4_demo_request->setDobDay($this->getRequestParameter('menu-dob-day'));
            $mlm_mt4_demo_request->setDobMonth($this->getRequestParameter('menu-dob-month'));
            $mlm_mt4_demo_request->setDobYear($this->getRequestParameter('menu-dob-year'));
            $mlm_mt4_demo_request->setRefId($this->getRequestParameter('referid'));
            $mlm_mt4_demo_request->setPassport($this->getRequestParameter('ssnumber'));
            $mlm_mt4_demo_request->setSubject($this->getRequestParameter('your-subject'));

            $mlm_mt4_demo_request->save();

            $subject = "感谢您申请博马思金融交易MT4帐户 Thank you for register RONUVA MT4 Account";
            //$subject = "Thank you for register RONUVA Demo Account";

            $body = "<table width='800' align='center' cellpadding='0' cellspacing='0' border='0'>
                    <tbody><tr>
                        <td valign='top' colspan='3'>
                            <table width='100%' cellpadding='0' cellspacing='0' border='0'>
                                <tbody>
                                <tr><td colspan='3' style='font-size:0;line-height:0' bgcolor='#0080C8'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='34'></td></tr>
                                <tr>
                                    <td style='font-size:0;line-height:0' width='201' valign='top'><img src='http://partner.ronuva.com/images/email/bg-top.png' width='160'></td>
                                    <td valign='top' width='551'>
                                        <table width='100%' cellpadding='0' cellspacing='0' border='0'>
                                            <tbody><tr><td style='font-size:0;line-height:0' colspan='2'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='71'></td></tr>
                                            <tr>
                                                <td valign='top' style='font-size:0;line-height:0' width='86'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='86' height='1'></td>
                                                <td valign='top' style='line-height:17px'>
                                                    <font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:14px;line-height:17px'>
												Dear <strong>" . $this->getRequestParameter('l-name') . " " . $this->getRequestParameter('f-name') . "</strong>,<br><br>

                                                Thank you for your recent application for a trading account with RONUVA.
                                                <br><br>
We are pleased to advise you that your account application has been accepted.
<br><br>
In order for us to open your account, there are a few pieces of information we need from you as soon as possible, so you can start to enjoy trading with RONUVA.
<br><br>
Please send us <strong>one</strong> certified** document from list (i) and <strong>two</strong> certified** documents from list (ii) below:
<br><br>

(i) ID Verification (non-expired)
<br>&nbsp;&nbsp;1. Passport; or
<br>&nbsp;&nbsp;2. Photocard driving licence; or
<br>&nbsp;&nbsp;3. National ID card
<br><br>
(ii) Address Verification*
<br>&nbsp;&nbsp;1. Bank statement; or
<br>&nbsp;&nbsp;2. Utility bill (gas, water, electric or land line telephone); or
<br>&nbsp;&nbsp;3. Credit card Statement.
<br><br>
<br><br>
Please scan the required documents and send them to us by email at <strong>accounts@ronuva.com</strong>
<br><br>
Once your documents have been successfully verified, we will advise you of your account number/login and password.
<br><br>
We look forward to your custom in the near future. Should you have any queries, please do not hesitate to contact us.
											</font>

											<br>
											<br>
											<br>
											<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:17px'>
											Forex, spread bets and CFDs are leveraged products. They may not be suitable for you as they carry a high degree of risk to your capital and you can lose more than your initial investment. You should ensure you understand all of the risks.
											</font>
                                                </td>
                                            </tr>
                                            <tr><td style='font-size:0;line-height:0' colspan=10'2'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='42'></td></tr>
									<tr>
										<td valign='top' width='551' colspan='2'>
											<table width='100%' cellpadding='0' cellspacing='0' border='0'>
												<tbody><tr>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='86'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='86' height='1'></td>


													<td style='font-size:0;line-height:0' width='85'>
														<table width='100%' cellpadding='0' cellspacing='0' border='0'>
															<tbody>
															<tr style='text-align:center;line-height:15px' align='center'>
																<td style='font-size:0;line-height:0'><img src='http://partner.ronuva.com/images/email/img-platform.gif' width='85' height='60'></td>
															</tr>
															<tr>
																<td style='text-align:center;line-height:15px' align='center'>
																	<font face='Arial, Verdana, sans-serif' size='3' color='#58584b' style='font-size:11px;line-height:15px'>
																		<strong>RONUVA<br> MT4 Terminal</strong>
																	</font>
																</td>
															</tr>
															<tr><td style='text-align:center;line-height:15px' align='center'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'></td></tr>
															<tr>
																<td style='text-align:center;line-height:15px' align='center'><a href='http://partner.ronuva.com/download/demoMt4' target='_blank'><img src='http://partner.ronuva.com/images/email/btn-download_cn.png' height='26' width='85' border='0'></a></td>
															</tr>
														</tbody></table>
													</td>

													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>

												</tr>
											</tbody></table>
										</td>
									</tr>
									<tr>
										<td valign='top' style='font-size:0;line-height:0' width='86'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='86' height='1'></td>
										<td valign='top' style='line-height:17px'>
										<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:14px;line-height:17px'>
                                                        亲爱的 <STRONG>" . $this->getRequestParameter('l-name') . " " . $this->getRequestParameter('f-name') . "</strong>，<br><br>
                                                        你的MT4帐户将使你可以进行贸易，使用MetaTrader 4可以允许你开发和测试您的交易策略。


                                                        感谢您申请RONUVA的交易账户。
                                                <br><br>
我们很高兴地告诉你，你的开户申请已经被接受。
<br><br>
您已选择（个人）以美元交易的账户。
<br><br>
为了让我们激活您的帐户，我们需要您尽快尽快提交以下的文件与资料:
<br><br>
请发送给我们<STRONG>一份</strong>（必须认证）**文件列表（i）及<STRONG>两份</strong>（必须认证）**文件列表（ii）段：
<br><br>

（ii）身份验证（未过期）
<BR>1. 护照;
<BR>2. 驾驶执照;
<BR>3. 国民身分证
<br><br>
（ii）地址验证码*
<BR>1. 银行对账单;
<BR>2. 水电费帐单（煤气，水，电或陆地线路电话）;
<BR>3. 信用卡对帐单。
<br><br>
*本文件必须是最近3个月内，文件里包括您的姓名和现住址，发行人及日期必须是清楚可见的。
<br><br>
<br><br>
请扫描所需的文件和电子邮件发送给我们在<strong> accounts@ronuva.com </strong>
<br><br>
您的文件得到了成功验证后，我们会通知您，您的帐户号码/用户名和密码。
<br><br>
我们期待着在不久的将来，您的自定义。如果您有任何疑问，请不要犹豫与我们联系。
                                                        <br>
                                                    </font>
                                                    <br>
                                                    <br>
                                                    <br>
                                                    <font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:17px'>
                                                    买外汇或者期货都是一种杠杆投资。他们可能不适合您，因为他们具有很高的风险，您可能会失去您最初的投资资金，所以您必须确保你了解所有的风险。
                                                    </font>

										</td>
									</tr>
									<tr><td style='font-size:0;line-height:0' colspan='2'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='42'></td></tr>
									<tr>
										<td valign='top' width='551' colspan='2'>
											<table width='100%' cellpadding='0' cellspacing='0' border='0'>
												<tbody><tr>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>
													<td style='font-size:0;line-height:0' width='85'>

													</td>
													<td style='font-size:0;line-height:0' width='86'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='86' height='1'></td>


													<td style='font-size:0;line-height:0' width='85'>
														<table width='100%' cellpadding='0' cellspacing='0' border='0'>
															<tbody>
															<tr style='text-align:center;line-height:15px' align='center'>
																<td style='font-size:0;line-height:0'><img src='http://partner.ronuva.com/images/email/img-platform.gif' width='85' height='60'></td>
															</tr>
															<tr>
																<td style='text-align:center;line-height:15px' align='center'>
																	<font face='Arial, Verdana, sans-serif' size='3' color='#58584b' style='font-size:11px;line-height:15px'>
																		<strong>RONUVA<br> MT4 Terminal</strong>
																	</font>
																</td>
															</tr>
															<tr><td style='font-size:0;line-height:0'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'></td></tr>
															<tr>
																<td style='text-align:center;line-height:15px' align='center'><a href='http://partner.ronuva.com/download/demoMt4' target='_blank'><img src='http://partner.ronuva.com/images/email/btn-download.png' height='26' width='85' border='0'></a></td>
															</tr>
														</tbody></table>
													</td>

													<td style='font-size:0;line-height:0' width='10'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='10' height='1'></td>

												</tr>
											</tbody></table>
										</td>
									</tr>
									<tr><td style='font-size:0;line-height:0' colspan='2'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='32'></td></tr>
									<tr>
										<td valign='top' style='font-size:0;line-height:0' width='86'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='86' height='1'></td>
										<td style='font-size:0;line-height:0' bgcolor='#0080C8'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='1'></td>
									</tr>
									<tr><td style='font-size:0;line-height:0' colspan='2'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'></td></tr>
									<tr>
										<td valign='top' style='line-height:15px;text-align:right' colspan='2' align='right'>
											<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
												<em>
													Best Regards,<br>
													<strong>RONUVA Account Opening Team</strong><br>
													E mail : admin@ronuva.com
												</em>
											</font>
										</td>
									</tr>
								</tbody></table>
							</td>
							<td style='font-size:0;line-height:0' width='48'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='48' height='1'></td>
						</tr>
					</tbody></table>
				</td>
			</tr>
			<tr>
				<td style='font-size:0;line-height:0' width='63'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='63' height='1'></td>
				<td valign='top' width='689'>
					<table width='100%' cellpadding='0' cellspacing='0' border='0'>
						<tbody><tr><td style='font-size:0;line-height:0'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='28'></td></tr>
						<tr>
							<td align='right' style='text-align:right;font-size:0;line-height:0'>
								<a href='http://ronuva.com/' target='_blank'><img src='http://partner.ronuva.com/images/email/logo.png' width='254' height='87' border='0'></a>

								<br>
								<p align='justify'>
									<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
											RONUVA is managed by RONUVA Capital Limited which is authorised and regulated in the New Zealand by the Financial Services Provider. FSP Register number is 252705. Registered Office: Level 8, 10/12 Scotia Place, Suite 11, Auckland City Centre, Auckland, 1010, New Zealand. Tel (+64) 93791159
											<br><br>RONUVA Capital Limited is a subsidiary of Royale Group Holding Inc. a public listed company in USA.
<br><br>CONFIDENTIALITY: This e-mail and any files transmitted with it are confidential and intended solely for the use of the recipient(s) only. Any review, retransmission, dissemination or other use of, or taking any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you have received this e-mail in error please notify the sender immediately and destroy the material whether stored on a computer or otherwise.
<br><br>DISCLAIMER: Any views or opinions presented within this e-mail are solely those of the author and do not necessarily represent those of RONUVA capital Limited, unless otherwise specifically stated. The content of this message does not constitute Investment Advice.
<br><br>RISK WARNING: Forex, spread bets, and CFDs carry a high degree of risk to your capital and it is possible to lose more than your initial investment. Only speculate with money you can afford to lose. As with any trading, you should not engage in it unless you understand the nature of the transaction you are entering into and, the true extent of your exposure to the risk of loss. These products may not be suitable for all investors, therefore if you do not fully understand the risks involved, please seek independent advice.
									</font>
								</p>
							</td>
						</tr>
						<tr><td style='font-size:0;line-height:0'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='16'></td></tr>
					</tbody></table>
				</td>
				<td style='font-size:0;line-height:0' width='48'><img src='http://partner.ronuva.com/images/email/transparent.gif' width='48' height='1'></td>
			</tr>
			<tr><td colspan='3' style='font-size:0;line-height:0' bgcolor='#0080C8'><img src='http://partner.ronuva.com/images/email/transparent.gif' height='34'></td></tr>
		</tbody></table>";

            //$sendMailService = new SendMailService();
            //$sendMailService->sendMail($this->getRequestParameter('your-email'), $this->getRequestParameter('l-name')." ".$this->getRequestParameter('f-name'), $subject, $body);
        }

        $arr = array(
            'error' => $error,
            'errorMsg' => $errorMsg
        );

        echo json_encode($arr);

        return sfView::HEADER_ONLY;
    }

    public function executeOpenLiveAccount_old()
    {
        $error = false;
        $errorMsg = "";

        if (!$this->getRequestParameter('referralId')) {
            $error = true;
            $errorMsg = "Referrer ID is required.";
        } else {
            $uplineDistDB = $this->getDistributorInformation($this->getRequestParameter('referralId'));
            if (!$uplineDistDB) {
                $error = true;
                $errorMsg = "Invalid referrer ID.";
            } else {
                //$fcode = $this->getRequestParameter('userName');
                //$password = $this->getRequestParameter('userpassword');
                $fcode = $this->generateFcode();
                $password = "";

                //******************* upline distributor ID
                //$treeStructure = $uplineDistDB->getTreeStructure() . "|" . $fcode . "|";
                //$treeLevel = $uplineDistDB->getTreeLevel() + 1;
                $treeStructure = "";
                $treeLevel = 0;

                // ****************************
                $mlm_distributor = new MlmDistributor();
                $mlm_distributor->setDistributorCode($fcode);
                $mlm_distributor->setUserId(Globals::SYSTEM_BROKER_ID);
                $mlm_distributor->setStatusCode(Globals::STATUS_PENDING);
                $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
                $mlm_distributor->setNickname($fcode);
                $mlm_distributor->setIc($this->getRequestParameter('ic'));
                if ($this->getRequestParameter('country') == 'China') {
                    $mlm_distributor->setCountry('China (PRC)');
                } else {
                    $mlm_distributor->setCountry($this->getRequestParameter('country'));
                }
                $mlm_distributor->setAddress($this->getRequestParameter('address'));
                $mlm_distributor->setAddress2($this->getRequestParameter('address2'));
                $mlm_distributor->setCity($this->getRequestParameter('city'));
                $mlm_distributor->setState($this->getRequestParameter('state'));
                $mlm_distributor->setPostcode($this->getRequestParameter('zip'));
                $mlm_distributor->setEmail($this->getRequestParameter('email'));
                $mlm_distributor->setAlternateEmail($this->getRequestParameter('alt_email'));
                $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
                $mlm_distributor->setGender($this->getRequestParameter('gender'));
                if ($this->getRequestParameter('dob')) {
                    list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
                    $mlm_distributor->setDob("$y-$m-$d");
                }
                $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
                $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccountNo'));
                $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));

                $mlm_distributor->setTreeLevel($treeLevel);
                $mlm_distributor->setTreeStructure($treeStructure);
                $mlm_distributor->setUplineDistId($uplineDistDB->getDistributorId());
                $mlm_distributor->setUplineDistCode($uplineDistDB->getDistributorCode());

                $mlm_distributor->setSignName($this->getRequestParameter('sign_name'));
                $mlm_distributor->setSignDate(date("Y/m/d h:i:s A"));
                $mlm_distributor->setTermCondition($this->getRequestParameter('term_condition'));

                $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_BROKER_ID));
                $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_BROKER_ID));
                $mlm_distributor->save();
            }
        }
        //print_r("error:".$error.",errorMsg:".$errorMsg);
        $arr = array(
            'error' => $error,
            'errorMsg' => $errorMsg
        );

        echo json_encode($arr);
        /****************************/
        /*****  Send email **********/
        /****************************/
        /*error_reporting(E_STRICT);

        date_default_timezone_set(date_default_timezone_get());

        include_once('class.phpmailer.php');

        $subject = $this->getContext()->getI18N()->__("Vital Universe Group Registration email notification", null, 'email');
        $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $mlm_distributor->getNickname()), 'email') . ",<p><p>

        <p>" . $this->getContext()->getI18N()->__("Your registration request has been successfully sent to Vital Universe Group", null, 'email') . "</p>
        <p><b>" . $this->getContext()->getI18N()->__("Trader ID", null) . ": " . $fcode . "</b>
        <p><b>" . $this->getContext()->getI18N()->__("Password", null) . ": " . $password . "</b>";

        $mail = new PHPMailer();
        $mail->IsMail(); // telling the class to use SMTP
        $mail->Host = Mails::EMAIL_HOST; // SMTP server
        $mail->Sender = Mails::EMAIL_FROM_NOREPLY;
        $mail->From = Mails::EMAIL_FROM_NOREPLY;
        $mail->FromName = Mails::EMAIL_FROM_NOREPLY_NAME;
        $mail->Subject = $subject;
        $mail->CharSet="utf-8";

        $text_body = $body;

        $mail->Body = $body;
        $mail->AltBody = $text_body;
        $mail->AddAddress($mlm_distributor->getEmail(), $mlm_distributor->getNickname());
        $mail->AddBCC("r9projecthost@gmail.com", "jason");

        if (!$mail->Send()) {
            echo $mail->ErrorInfo;
        }*/
        return sfView::HEADER_ONLY;
    }

    // **********************************************************************************************
    // *******************   ~ end      For broker registeration       end ~   **********************
    // **********************************************************************************************

    public function executeVerifySameGroupSponsorId()
    {
        //var_dump($this->getUser()->getAttribute(Globals::SESSION_USERNAME));
        $sponsorId = $this->getRequestParameter('sponsorId');
        //var_dump($sponsorId);

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $existDist = MlmDistributorPeer::doSelectOne($c);

        $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $this->getUser()->getAttribute(Globals::SESSION_DISTID) . "|%", Criteria::LIKE);
        $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        $arr = "";
        if (!$existUser && $existDist) {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
            $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $existDist->getDistributorId() . "|%", Criteria::LIKE);
            $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
            $existUser = MlmDistributorPeer::doSelectOne($c);

            if ($existUser) {
                $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
                $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
                $existUser = MlmDistributorPeer::doSelectOne($c);
            }
        }

        if ($existUser) {
            //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $arr = array(
                'userId' => $existUser->getDistributorId(),
                'userName' => $existUser->getDistributorCode(),
                'fullname' => $existUser->getFullName(),
                'nickname' => $existUser->getNickname()
            );
            //}
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeVerifySponsorId()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');

        $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        $arr = "";
        if ($existUser) {
            //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $arr = array(
                'userId' => $existUser->getDistributorId(),
                'userName' => $existUser->getDistributorCode(),
                'fullname' => $existUser->getFullName(),
                'nickname' => $existUser->getNickname()
            );
            //}
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executePreVerifyMemberRegister()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');
        $cardNumber = $this->getRequestParameter('cardNumber');
        $cvvNumber = $this->getRequestParameter('cvvNumber');

        $c = new Criteria();
        $c->add(MlmMemberCardPeer::CARD_NUMBER, $cardNumber);
        $c->add(MlmMemberCardPeer::CVV_NUMBER, $cvvNumber);
        $c->add(MlmMemberCardPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existMemberCard = MlmMemberCardPeer::doSelectOne($c);

        $arr = array(
            'error' => "false",
            'errorMessage' => ""
        );

        if (!$existMemberCard) {
            $arr = array(
                'error' => "true",
                'errorMessage' => "Invalid Card Number."
            );
        } else {
            $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
            $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
            $existUser = MlmDistributorPeer::doSelectOne($c);


            if ($existUser) {
                //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
                $arr = array(
                    'userId' => $existUser->getDistributorId(),
                    'userName' => $existUser->getDistributorCode(),
                    'fullname' => $existUser->getFullName(),
                    'nickname' => $existUser->getNickname(),
                    'error' => "false",
                    'errorMessage' => ""
                );
                //}
            } else {
                $arr = array(
                    'error' => "true",
                    'errorMessage' => "Invalid Referrer ID."
                );
            }
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    function generatePaymentReference()
    {
        $max_digit = 9999999999;
        $digit = 12;

        while (true) {
            $fcode = rand(1000000000, $max_digit) . "";
            //$fcode = str_pad($fcode, $digit, "0", STR_PAD_LEFT);
            /*
            for ($x=0; $x < ($digit - strlen($fcode)); $x++) {
                $fcode = "0".$fcode;
            }
			*/
            $c = new Criteria();
            $c->add(MlmDistEpointPurchasePeer::PAYMENT_REFERENCE, $fcode);
            $existCode = MlmDistEpointPurchasePeer::doSelectOne($c);

            if (!$existCode) {
                break;
            }
        }
        return $fcode;
    }

    public function executeVerifyActiveSponsorId()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');

        //$array = explode(',', Globals::STATUS_ACTIVE.",".Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
        $c->add(MlmDistributorPeer::RANK_ID, 1, Criteria::NOT_EQUAL);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        $arr = "";
        if ($existUser) {
            //if ($existUser->getDistributorId() <> $this->getUser()->getAttribute(Globals::SESSION_DISTID)) {
            $arr = array(
                'userId' => $existUser->getDistributorId(),
                'userName' => $existUser->getDistributorCode(),
                'fullname' => $existUser->getFullName(),
                'nickname' => $existUser->getNickname()
            );
            //}
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeFetchPackage()
    {
        $account = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $ecashAccount = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

        $arr = array(
            'packageId' => 0,
            'point' => 0,
            'ecash' => 0,
            'package' => ""
        );
        if (($account) && ($ecashAccount)) {
            $max = $ecashAccount->getBalance();

            if ($account->getBalance() > $ecashAccount->getBalance())
                $max = $account->getBalance();

            $c = new Criteria();
            //$c->add(MlmPackagePeer::PRICE, $max, Criteria::LESS_EQUAL);
            if ($this->getRequestParameter('publicPurchase') == "") {
                $c->add(MlmPackagePeer::PUBLIC_PURCHASE, Globals::YES);
            } else {
                $c->add(MlmPackagePeer::PUBLIC_PURCHASE, $this->getRequestParameter('publicPurchase'));
            }

            $c->addDescendingOrderByColumn(MlmPackagePeer::PRICE);

            $packages = MlmPackagePeer::doSelect($c);

            $packageArray = array();
            $count = 0;
            foreach ($packages as $package) {
                $packageArray[$count]["packageId"] = $package->getPackageId();
                $packageArray[$count]["name"] = $this->getContext()->getI18N()->__($package->getPackageName());
                $packageArray[$count]["price"] = $package->getPrice();
                $count++;
            }

            $arr = array(
                'point' => $account->getBalance(),
                'ecash' => $ecashAccount->getBalance(),
                'package' => $packageArray
            );
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeFetchTopupPackage()
    {
        $account = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $ecashAccount = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);

        $distPackage = MlmPackagePeer::retrieveByPK($distDB->getRankId());
        $currentPackageAmount = $distPackage->getPrice();

        if ($currentPackageAmount == null)
            $currentPackageAmount = 99999999;

        $arr = array(
            'packageId' => 0,
            'point' => 0,
            'ecash' => 0,
            'package' => ""
        );
        if (($account) && ($ecashAccount)) {
            $totalEcash = $ecashAccount->getBalance() + $currentPackageAmount;
            $totalEpoint = $account->getBalance() + $currentPackageAmount;

            $max = $totalEcash;

            if ($totalEpoint > $totalEcash)
                $max = $totalEpoint;

            $c = new Criteria();
            $c->add(MlmPackagePeer::PRICE, $max, Criteria::LESS_EQUAL);
            $c->addAnd(MlmPackagePeer::PRICE, $currentPackageAmount, Criteria::GREATER_THAN);
            $c->addAnd(MlmPackagePeer::PRICE, null, Criteria::ISNOTNULL);

            if ($this->getRequestParameter('publicPurchase') == "") {
                $c->add(MlmPackagePeer::PUBLIC_PURCHASE, Globals::YES);
            } else {
                $c->add(MlmPackagePeer::PUBLIC_PURCHASE, $this->getRequestParameter('publicPurchase'));
            }

            $c->addDescendingOrderByColumn(MlmPackagePeer::PRICE);

            $packages = MlmPackagePeer::doSelect($c);

            $packageArray = array();
            $count = 0;
            foreach ($packages as $package) {
                $packageArray[$count]["packageId"] = $package->getPackageId();
                $packageArray[$count]["name"] = $this->getContext()->getI18N()->__($package->getPackageName());
                $packageArray[$count]["price"] = $package->getPrice() - $currentPackageAmount;
                $count++;
            }

            $arr = array(
                'point' => $totalEpoint,
                'ecash' => $totalEcash,
                'package' => $packageArray
            );
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeSummary()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $this->pendingDistributors = MlmDistributorPeer::doSelect($c);

        $c = new Criteria();
        $c->add(MlmAnnouncementPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->addDescendingOrderByColumn(MlmAnnouncementPeer::CREATED_ON);
        $c->setLimit(5);
        $this->announcements = MlmAnnouncementPeer::doSelect($c);

        $distributor = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distributor);

        $ecash = 0;
        $epoint = 0;
        $pv = 0;
        $groupPv = 0;
        $totalNetworks = 0;
        $ranking = "";
        $currencyCode = "";
        $lastLogin = "";

        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_SYSTEM_CURRENCY);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $currencyCode = $settingDB->getSettingValue();
        }
        if ($distributor) {
            $existUser = AppUserPeer::retrieveByPK($distributor->getUserId());

            if ($existUser) {
                $lastLogin = $existUser->getLastLoginDatetime();
            }

            $packageDB = MlmPackagePeer::retrieveByPK($distributor->getRankId());
            $ranking = $packageDB->getPackageName();

            $ecash = $this->getAccountBalance($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_ECASH);
            $epoint = $this->getAccountBalance($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_EPOINT);
            $pv = $this->getAccountBalance($distributor->getDistributorId(), Globals::ACCOUNT_TYPE_PV);

            $monthAdded = 1; // testing for this month
            //$monthAdded = 0; // production

            $queryStartDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded - 1), 1, date("Y")));
            $queryDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded), 0, date("Y")));
            $groupPv = $this->getTotalGroupPV($distributor->getDistributorId(), $queryStartDate, $queryDate) - $pv;

            $c = new Criteria();
            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distributor->getDistributorId());
            $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $totalNetworks = MlmDistributorPeer::doCount($c);
        }

        $this->ecash = $ecash;
        $this->epoint = $epoint;
        $this->pv = $pv;
        $this->groupPv = $groupPv;
        $this->totalNetworks = $totalNetworks;
        $this->ranking = $ranking;
        $this->colorArr = $this->getRankColorArr();
        $this->currencyCode = $currencyCode;
        $this->distributor = $distributor;
        $this->lastLogin = $lastLogin;
    }

    public function executeAnnouncementList()
    {
        $c = new Criteria();
        $c->add(MlmAnnouncementPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->addDescendingOrderByColumn(MlmAnnouncementPeer::CREATED_ON);
        $c->setLimit(10);
        $this->announcements = MlmAnnouncementPeer::doSelect($c);
    }

    public function executeBonusDetailList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();

        /******   total records  *******/
        $c = new Criteria();
        $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        //$c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::ACCOUNT_LEDGER_ACTION_DRB);
        $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, $this->getRequestParameter('filterBonusType'));
        $totalRecords = MlmDistCommissionLedgerPeer::doCount($c);

        /******   total filtered records  *******/
        if ($this->getRequestParameter('filterMonth') != "" && $this->getRequestParameter('filterYear') != "") {
            $dateUtil = new DateUtil();
            $month = $this->getRequestParameter('filterMonth');
            $year = $this->getRequestParameter('filterYear');
            $d = $dateUtil->getMonth($month, $year);

            $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
            $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

            $c->add(MlmDistCommissionLedgerPeer::CREATED_ON, $firstOfMonth, Criteria::GREATER_EQUAL);
            $c->addAnd(MlmDistCommissionLedgerPeer::CREATED_ON, $lastOfMonth, Criteria::LESS_EQUAL);
        }

        $totalFilteredRecords = MlmDistCommissionLedgerPeer::doCount($c);

        /******   sorting  *******/
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                if ("asc" == $this->getRequestParameter('sSortDir_' . $i)) {
                    $c->addAscendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                } else {
                    $c->addDescendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                }
            }
        }

        /******   pagination  *******/
        $pager = new sfPropelPager('MlmDistCommissionLedger', $limit);
        $pager->setCriteria($c);
        $pager->setPage(($offset / $limit) + 1);
        $pager->init();

        foreach ($pager->getResults() as $result) {
            $extraRemark = "";
            if (Globals::STATUS_COMPLETE == $result->getStatusCode()) {
                $dateString = $result->getUpdatedOn();
                $dateArr = explode(" ", $dateString);
                $extraRemark = "Successful credited into MT4 Fund (" . $dateArr[0] . ")";
            }
            $arr[] = array(
                $result->getCommissionId() == null ? "0" : $result->getCommissionId(),
                $result->getCreatedOn() == null ? "" : $result->getCreatedOn(),
                $result->getCommissionType() == null ? ""
                        : $this->getContext()->getI18N()->__($result->getCommissionType()),
                $result->getCredit() == null ? "0" : number_format($result->getCredit(), 2),
                $result->getDebit() == null ? "0" : number_format($result->getDebit(), 2),
                $result->getRemark() == null ? "" : $result->getRemark(),
                $extraRemark
            );
        }

        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeDelete()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $c->addAnd(MlmDistributorPeer::DISTRIBUTOR_ID, $this->getRequestParameter('distid'));
        $mlmDistributor = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($mlmDistributor);

        $mlmDistributor->setStatusCode(Globals::STATUS_CANCEL);
        $mlmDistributor->save();

        $appUser = AppUserPeer::retrieveByPk($mlmDistributor->getUserId());
        $this->forward404Unless($appUser);
        $appUser->setStatusCode(Globals::STATUS_CANCEL);
        $appUser->save();

        return $this->redirect('/member/summary');
    }

    public function executeVerifyTransactionPassword()
    {
        $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
        $c->add(AppUserPeer::USERPASSWORD2, $this->getRequestParameter('transactionPassword'));
        $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
        //$c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->add(AppUserPeer::STATUS_CODE, $array, Criteria::IN);

        $existUser = AppUserPeer::doSelectOne($c);

        if ($existUser) {
            echo 'true';
        } else {
            echo 'false';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeActivateMember()
    {
        $sponsorId = $this->getRequestParameter('sponsorId');
        //$sponsorId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
        $transactionPassword = $this->getRequestParameter('transactionPassword');
        $packageId = $this->getRequestParameter('packageId');
        $paymentType = "epoint";
        //$paymentType = $this->getRequestParameter('paymentType');
        $error = false;
        $errorMsg = "";

        //$array = explode(',', Globals::STATUS_ACTIVE.",".Globals::STATUS_PENDING);
        $c = new Criteria();
        $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
        $c->add(AppUserPeer::USERPASSWORD2, $transactionPassword);
        $c->add(AppUserPeer::USER_ROLE, Globals::ROLE_DISTRIBUTOR);
        $c->add(AppUserPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        //$c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);

        $existUser = AppUserPeer::doSelectOne($c);
        if (!$existUser) {
            $error = true;
            $errorMsg = $this->getContext()->getI18N()->__("Invalid Security Password.");
        }

        $packageDB = null;
        if (!$error) {
            $packageDB = MlmPackagePeer::retrieveByPK($packageId);
            $this->forward404Unless($packageDB);
            if (!$packageDB) {
                $error = true;
                $errorMsg = $this->getContext()->getI18N()->__("Invalid Package.");
            }
        }

        if (!$error) {
            if ("epoint" == $paymentType) {
                $balance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
                if ($balance < $packageDB->getPrice()) {
                    $error = true;
                    $errorMsg = $this->getContext()->getI18N()->__("Insufficient e-Point.");
                }
            } else if ("ecash" == $paymentType) {
                $balance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
                if ($balance < $packageDB->getPrice()) {
                    $error = true;
                    $errorMsg = $this->getContext()->getI18N()->__("Insufficient e-Wallet.");
                }
            } else {
                $error = true;
                $errorMsg = $this->getContext()->getI18N()->__("Invalid Action.");
            }
        }

        if (!$error) {
            $distDB = MlmDistributorPeer::retrieveByPK($sponsorId);
            $this->doActivateAccount($distDB->getUplineDistId(), $sponsorId, $packageId, $paymentType);
        }
        $arr = array(
            'error' => $error
        , 'errorMsg' => $errorMsg
        );
        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executePlacementTree()
    {

        if ($this->getRequestParameter('doAction') == "save") {
            $uplineDistCode = $this->getRequestParameter('uplineDistCode');
            $uplinePosition = $this->getRequestParameter('uplinePosition');
            $sponsorDistId = $this->getRequestParameter('sponsorDistId');

            $uplineDistDB = $this->getDistributorInformation($uplineDistCode);
            $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $sponsorDB = MlmDistributorPeer::retrieveByPk($sponsorDistId);
            $this->forward404Unless($distDB);
            $this->forward404Unless($sponsorDB);

            $treeStructure = $uplineDistDB->getPlacementTreeStructure() . "|" . $sponsorDB->getDistributorId() . "|";
            $treeLevel = $uplineDistDB->getPlacementTreeLevel() + 1;

            $sponsorDB->setPlacementDatetime(date("Y/m/d h:i:s A"));
            $sponsorDB->setPlacementPosition($uplinePosition);
            //$sponsorDB->setUplineDistId($uplineDistDB->getDistributorId());
            //$sponsorDB->setUplineDistCode($uplineDistDB->getDistributorCode());
            $sponsorDB->setPlacementTreeStructure($treeStructure);
            $sponsorDB->setPlacementTreeLevel($treeLevel);
            $sponsorDB->setTreeUplineDistId($uplineDistDB->getDistributorId());
            $sponsorDB->setTreeUplineDistCode($uplineDistDB->getDistributorCode());
            $sponsorDB->save();

            $sponsoredPackageDB = MlmPackagePeer::retrieveByPK($sponsorDB->getRankId());
            $this->forward404Unless($sponsoredPackageDB);
            $pairingPoint = $sponsoredPackageDB->getPrice();
            /*if ($sponsoredPackageDB->getPackageId() == Globals::MAX_PACKAGE_ID) {
                $pairingPoint = $amountNeeded;
            }*/
            // recalculate Total left and total right for $uplineDistDB
            $arrs = explode("|", $uplineDistDB->getPlacementTreeStructure());
            for ($x = count($arrs); $x > 0; $x--) {
                if ($arrs[$x] == "") {
                    continue;
                }
                $uplineDistDB = $this->getDistributorInformation($arrs[$x]);
                $this->forward404Unless($uplineDistDB);
                $totalLeft = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_LEFT);
                $totalRight = $this->getTotalPosition($arrs[$x], Globals::PLACEMENT_RIGHT);
                $uplineDistDB->setTotalLeft($totalLeft);
                $uplineDistDB->setTotalRight($totalRight);
                $uplineDistDB->save();
            }

            /******************************/
            /*  store Pairing points
            /******************************/
            if ($sponsorDB->getTreeUplineDistId() != 0 && $sponsorDB->getTreeUplineDistCode() != null) {
                $level = 0;
                $uplineDistDB = MlmDistributorPeer::retrieveByPk($sponsorDB->getTreeUplineDistId());
                $sponsoredDistributorCode = $sponsorDB->getDistributorCode();
                while ($level < 100) {
                    //var_dump($uplineDistDB->getUplineDistId());
                    //var_dump($uplineDistDB->getUplineDistCode());
                    //print_r("<br>");
                    $c = new Criteria();
                    $c->add(MlmDistPairingPeer::DIST_ID, $uplineDistDB->getDistributorId());
                    $sponsorDistPairingDB = MlmDistPairingPeer::doSelectOne($c);

                    $addToLeft = 0;
                    $addToRight = 0;
                    $leftBalance = 0;
                    $rightBalance = 0;
                    if (!$sponsorDistPairingDB) {
                        $sponsorDistPairingDB = new MlmDistPairing();
                        $sponsorDistPairingDB->setDistId($uplineDistDB->getDistributorId());

                        $packageDB = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
                        $this->forward404Unless($packageDB);

                        $sponsorDistPairingDB->setLeftBalance($leftBalance);
                        $sponsorDistPairingDB->setRightBalance($rightBalance);
                        $sponsorDistPairingDB->setFlushLimit($packageDB->getDailyMaxPairing());
                        $sponsorDistPairingDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    } else {
                        $leftBalance = $sponsorDistPairingDB->getLeftBalance();
                        $rightBalance = $sponsorDistPairingDB->getRightBalance();
                    }
                    $sponsorDistPairingDB->setLeftBalance($leftBalance + $addToLeft);
                    $sponsorDistPairingDB->setRightBalance($rightBalance + $addToRight);
                    $sponsorDistPairingDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingDB->save();

                    $c = new Criteria();
                    $c->add(MlmDistPairingLedgerPeer::DIST_ID, $uplineDistDB->getDistributorId());
                    $c->add(MlmDistPairingLedgerPeer::LEFT_RIGHT, $uplinePosition);
                    $c->addDescendingOrderByColumn(MlmDistPairingLedgerPeer::CREATED_ON);
                    $sponsorDistPairingLedgerDB = MlmDistPairingLedgerPeer::doSelectOne($c);

                    $legBalance = 0;
                    if ($sponsorDistPairingLedgerDB) {
                        $legBalance = $sponsorDistPairingLedgerDB->getBalance();
                    }

                    $sponsorDistPairingledger = new MlmDistPairingLedger();
                    $sponsorDistPairingledger->setDistId($uplineDistDB->getDistributorId());
                    $sponsorDistPairingledger->setLeftRight($uplinePosition);
                    $sponsorDistPairingledger->setTransactionType(Globals::PAIRING_LEDGER_REGISTER);
                    $sponsorDistPairingledger->setCredit($pairingPoint);
                    $sponsorDistPairingledger->setDebit(0);
                    $sponsorDistPairingledger->setBalance($legBalance + $pairingPoint);
                    $sponsorDistPairingledger->setRemark("PAIRING POINT AMOUNT (" . $sponsoredDistributorCode . ")");
                    $sponsorDistPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistPairingledger->save();

                    $this->revalidatePairing($uplineDistDB->getDistributorId(), $uplinePosition);

                    if ($uplineDistDB->getTreeUplineDistId() == 0 || $uplineDistDB->getTreeUplineDistCode() == null) {
                        break;
                    }

                    $uplinePosition = $uplineDistDB->getPlacementPosition();
                    $uplineDistDB = MlmDistributorPeer::retrieveByPk($uplineDistDB->getTreeUplineDistId());
                    $level++;
                }
            }
            /******************************/
            /*  Pairing             ~ END ~
            /******************************/
            return $this->redirect('/member/placementTree?distcode=' . $this->getRequestParameter('distcode', $this->getUser()->getAttribute(Globals::SESSION_USERNAME)));
        }
        $distcode = $this->getRequestParameter('distcode', $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
        $pageDirection = $this->getRequestParameter('p', "");

        $this->pageDirection = $pageDirection;
        $anode = array();
        //      0
        //  1       2
        //3   4   5   6

        // TO_HIDE_DIST_GROUP
        $hideDistGroup = false;
        $pos = strrpos(Globals::TO_HIDE_DIST_GROUP, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
        if ($pos === false) { // note: three equal signs

        } else {
            $hideDistGroup = true;
        }
        $this->hideDistGroup = $hideDistGroup;
        // TO_HIDE_DIST_GROUP end ~

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distcode);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $this->getUser()->getAttribute(Globals::SESSION_DISTID) . "|%", Criteria::LIKE);
        $distDB = MlmDistributorPeer::doSelectOne($c);

        if (!$distDB) {
            $this->errorSearch = true;
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
            $distDB = MlmDistributorPeer::doSelectOne($c);
        }

        // TO_HIDE_DIST_GROUP
        if ($hideDistGroup) {
            $pos = strrpos($distDB->getPlacementTreeStructure(), Globals::HIDE_DIST_GROUP);
            if ($pos === false) { // note: three equal signs

            } else {
                $this->errorSearch = true;
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
                $distDB = MlmDistributorPeer::doSelectOne($c);
            }
        }
        // TO_HIDE_DIST_GROUP end ~

        $leftOnePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        $rightTwoPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["distCode"] = $distDB->getDistributorCode();
        $anode[0]["_self"] = $distDB;
        $anode[0]["_left"] = $leftOnePlacement;
        $anode[0]["_right"] = $rightTwoPlacement;
        $anode[0]["_available"] = false;
        $anode[0]["_left_this_month_sales"] = $this->getThisMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        $anode[0]["_right_this_month_sales"] = $this->getThisMonthSales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["_dist_pairing_ledger"] = $this->queryDistPairing($distDB->getDistributorId());
        $anode[0]["_accumulate_left"] = $this->getLegTotalMember($leftOnePlacement);
        $anode[0]["_accumulate_right"] = $this->getLegTotalMember($rightTwoPlacement);
        //        $anode[0]["_accumulate_left"] = $this->getAccumulateGroupBvs($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        //        $anode[0]["_accumulate_right"] = $this->getAccumulateGroupBvs($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
        $anode[0]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
        $anode[0]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[0]["_today_left"];
        $anode[0]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[0]["_today_right"];
        $anode[0]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
        $anode[0]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);

        if ($leftOnePlacement == null) {
            $anode[1]["distCode"] = "";
            $anode[1]["_self"] = new MlmDistributor();
            $anode[1]["_left"] = null;
            $anode[1]["_right"] = null;
            $anode[1]["_available"] = true;
            $anode[1]["_left_this_month_sales"] = null;
            $anode[1]["_right_this_month_sales"] = null;
            $anode[1]["_dist_pairing_ledger"] = null;
            $anode[1]["_accumulate_left"] = null;
            $anode[1]["_accumulate_right"] = null;
            $anode[1]["_today_left"] = null;
            $anode[1]["_today_right"] = null;
            $anode[1]["_carry_left"] = null;
            $anode[1]["_carry_right"] = null;
            $anode[1]["_sales_left"] = null;
            $anode[1]["_sales_right"] = null;

            $anode[3]["distCode"] = "";
            $anode[3]["_self"] = new MlmDistributor();
            $anode[3]["_left"] = null;
            $anode[3]["_right"] = null;
            $anode[3]["_available"] = false;
            $anode[3]["_left_this_month_sales"] = null;
            $anode[3]["_right_this_month_sales"] = null;
            $anode[3]["_dist_pairing_ledger"] = null;
            $anode[3]["_accumulate_left"] = null;
            $anode[3]["_accumulate_right"] = null;
            $anode[3]["_today_left"] = null;
            $anode[3]["_today_right"] = null;
            $anode[3]["_carry_left"] = null;
            $anode[3]["_carry_right"] = null;
            $anode[3]["_sales_left"] = null;
            $anode[3]["_sales_right"] = null;

            $anode[4]["distCode"] = "";
            $anode[4]["_self"] = new MlmDistributor();
            $anode[4]["_left"] = null;
            $anode[4]["_right"] = null;
            $anode[4]["_available"] = false;
            $anode[4]["_left_this_month_sales"] = null;
            $anode[4]["_right_this_month_sales"] = null;
            $anode[4]["_dist_pairing_ledger"] = null;
            $anode[4]["_accumulate_left"] = null;
            $anode[4]["_accumulate_right"] = null;
            $anode[4]["_today_left"] = null;
            $anode[4]["_today_right"] = null;
            $anode[4]["_carry_left"] = null;
            $anode[4]["_carry_right"] = null;
            $anode[4]["_sales_left"] = null;
            $anode[4]["_sales_right"] = null;

        } else {
            $distDB = $this->getDistributorInformation($leftOnePlacement->getDistributorCode());
            $leftThreePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $rightFourPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);

            $anode[1]["distCode"] = $leftOnePlacement->getDistributorCode();
            $anode[1]["_self"] = $distDB;
            $anode[1]["_left"] = $leftThreePlacement;
            $anode[1]["_right"] = $rightFourPlacement;
            $anode[1]["_available"] = false;
            $anode[1]["_left_this_month_sales"] = $this->getThisMonthSales($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[1]["_right_this_month_sales"] = $this->getThisMonthSales($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[1]["_dist_pairing_ledger"] = $this->queryDistPairing($leftOnePlacement->getDistributorId());
            $anode[1]["_accumulate_left"] = $this->getLegTotalMember($leftThreePlacement);
            $anode[1]["_accumulate_right"] = $this->getLegTotalMember($rightFourPlacement);
            //            $anode[1]["_accumulate_left"] = $this->getAccumulateGroupBvs($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            //            $anode[1]["_accumulate_right"] = $this->getAccumulateGroupBvs($leftOnePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[1]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[1]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[1]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[1]["_today_left"];
            $anode[1]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[1]["_today_right"];
            $anode[1]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
            $anode[1]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);

            if ($leftThreePlacement == null) {
                $anode[3]["distCode"] = "";
                $anode[3]["_self"] = new MlmDistributor();
                $anode[3]["_left"] = null;
                $anode[3]["_right"] = null;
                $anode[3]["_available"] = true;
                $anode[3]["_left_this_month_sales"] = null;
                $anode[3]["_right_this_month_sales"] = null;
                $anode[3]["_dist_pairing_ledger"] = null;
                $anode[3]["_accumulate_left"] = null;
                $anode[3]["_accumulate_right"] = null;
                $anode[3]["_today_left"] = null;
                $anode[3]["_today_right"] = null;
                $anode[3]["_carry_left"] = null;
                $anode[3]["_carry_right"] = null;
                $anode[3]["_sales_left"] = null;
                $anode[3]["_sales_right"] = null;
            } else {
                $distOne = $this->getPlacementDistributorInformation($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $distTwo = $this->getPlacementDistributorInformation($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);

                $distDB = $this->getDistributorInformation($leftThreePlacement->getDistributorCode());
                $anode[3]["distCode"] = $leftThreePlacement->getDistributorCode();
                $anode[3]["_self"] = $distDB;
                $anode[3]["_left"] = null;
                $anode[3]["_right"] = null;
                $anode[3]["_available"] = false;
                $anode[3]["_left_this_month_sales"] = $this->getThisMonthSales($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[3]["_right_this_month_sales"] = $this->getThisMonthSales($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[3]["_dist_pairing_ledger"] = $this->queryDistPairing($leftThreePlacement->getDistributorId());
                $anode[3]["_accumulate_left"] = $this->getLegTotalMember($distOne);
                $anode[3]["_accumulate_right"] = $this->getLegTotalMember($distTwo);
                //                $anode[3]["_accumulate_left"] = $this->getAccumulateGroupBvs($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                //                $anode[3]["_accumulate_right"] = $this->getAccumulateGroupBvs($leftThreePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[3]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[3]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[3]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[3]["_today_left"];
                $anode[3]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[3]["_today_right"];
                $anode[3]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
                $anode[3]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);
            }
            if ($rightFourPlacement == null) {
                $anode[4]["distCode"] = "";
                $anode[4]["_self"] = new MlmDistributor();
                $anode[4]["_left"] = null;
                $anode[4]["_right"] = null;
                $anode[4]["_available"] = true;
                $anode[4]["_left_this_month_sales"] = null;
                $anode[4]["_right_this_month_sales"] = null;
                $anode[4]["_dist_pairing_ledger"] = null;
                $anode[4]["_accumulate_left"] = null;
                $anode[4]["_accumulate_right"] = null;
                $anode[4]["_today_left"] = null;
                $anode[4]["_today_right"] = null;
                $anode[4]["_carry_left"] = null;
                $anode[4]["_carry_right"] = null;
                $anode[4]["_sales_left"] = null;
                $anode[4]["_sales_right"] = null;
            } else {
                $distDB = $this->getDistributorInformation($rightFourPlacement->getDistributorCode());

                $distOne = $this->getPlacementDistributorInformation($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $distTwo = $this->getPlacementDistributorInformation($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);

                $anode[4]["distCode"] = $rightFourPlacement->getDistributorCode();
                $anode[4]["_self"] = $distDB;
                $anode[4]["_left"] = null;
                $anode[4]["_right"] = null;
                $anode[4]["_available"] = false;
                $anode[4]["_left_this_month_sales"] = $this->getThisMonthSales($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[4]["_right_this_month_sales"] = $this->getThisMonthSales($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[4]["_dist_pairing_ledger"] = $this->queryDistPairing($rightFourPlacement->getDistributorId());

                $anode[4]["_accumulate_left"] = $this->getLegTotalMember($distOne);
                $anode[4]["_accumulate_right"] = $this->getLegTotalMember($distTwo);
                //                $anode[4]["_accumulate_left"] = $this->getAccumulateGroupBvs($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                //                $anode[4]["_accumulate_right"] = $this->getAccumulateGroupBvs($rightFourPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[4]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[4]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[4]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[4]["_today_left"];
                $anode[4]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[4]["_today_right"];
                $anode[4]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
                $anode[4]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);
            }
        }

        if ($rightTwoPlacement == null) {
            $anode[2]["distCode"] = "";
            $anode[2]["_self"] = new MlmDistributor();
            $anode[2]["_left"] = null;
            $anode[2]["_right"] = null;
            $anode[2]["_available"] = true;
            $anode[2]["_left_this_month_sales"] = null;
            $anode[2]["_right_this_month_sales"] = null;
            $anode[2]["_dist_pairing_ledger"] = null;
            $anode[2]["_accumulate_left"] = null;
            $anode[2]["_accumulate_right"] = null;
            $anode[2]["_today_left"] = null;
            $anode[2]["_today_right"] = null;
            $anode[2]["_carry_left"] = null;
            $anode[2]["_carry_right"] = null;
            $anode[2]["_sales_left"] = null;
            $anode[2]["_sales_right"] = null;

            $anode[5]["distCode"] = "";
            $anode[5]["_self"] = new MlmDistributor();
            $anode[5]["_left"] = null;
            $anode[5]["_right"] = null;
            $anode[5]["_available"] = false;
            $anode[5]["_left_this_month_sales"] = null;
            $anode[5]["_right_this_month_sales"] = null;
            $anode[5]["_dist_pairing_ledger"] = null;
            $anode[5]["_accumulate_left"] = null;
            $anode[5]["_accumulate_right"] = null;
            $anode[5]["_today_left"] = null;
            $anode[5]["_today_right"] = null;
            $anode[5]["_carry_left"] = null;
            $anode[5]["_carry_right"] = null;
            $anode[5]["_sales_left"] = null;
            $anode[5]["_sales_right"] = null;

            $anode[6]["distCode"] = "";
            $anode[6]["_self"] = new MlmDistributor();
            $anode[6]["_left"] = null;
            $anode[6]["_right"] = null;
            $anode[6]["_available"] = false;
            $anode[6]["_left_this_month_sales"] = null;
            $anode[6]["_right_this_month_sales"] = null;
            $anode[6]["_dist_pairing_ledger"] = null;
            $anode[6]["_accumulate_left"] = null;
            $anode[6]["_accumulate_right"] = null;
            $anode[6]["_today_left"] = null;
            $anode[6]["_today_right"] = null;
            $anode[6]["_carry_left"] = null;
            $anode[6]["_carry_right"] = null;
            $anode[6]["_sales_left"] = null;
            $anode[6]["_sales_right"] = null;
        } else {
            $distDB = $this->getDistributorInformation($rightTwoPlacement->getDistributorCode());
            $leftFivePlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $rightSixPlacement = $this->getPlacementDistributorInformation($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);

            $anode[2]["distCode"] = $rightTwoPlacement->getDistributorCode();
            $anode[2]["_self"] = $distDB;
            $anode[2]["_left"] = $leftFivePlacement;
            $anode[2]["_right"] = $rightSixPlacement;
            $anode[2]["_available"] = false;
            $anode[2]["_left_this_month_sales"] = $this->getThisMonthSales($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[2]["_right_this_month_sales"] = $this->getThisMonthSales($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[2]["_dist_pairing_ledger"] = $this->queryDistPairing($rightTwoPlacement->getDistributorId());

            $anode[2]["_accumulate_left"] = $this->getLegTotalMember($leftFivePlacement);
            $anode[2]["_accumulate_right"] = $this->getLegTotalMember($rightSixPlacement);
            //            $anode[2]["_accumulate_left"] = $this->getAccumulateGroupBvs($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
            //            $anode[2]["_accumulate_right"] = $this->getAccumulateGroupBvs($rightTwoPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[2]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
            $anode[2]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
            $anode[2]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[2]["_today_left"];
            $anode[2]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[2]["_today_right"];
            $anode[2]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
            $anode[2]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);


            if ($leftFivePlacement == null) {
                $anode[5]["distCode"] = "";
                $anode[5]["_self"] = new MlmDistributor();
                $anode[5]["_left"] = null;
                $anode[5]["_right"] = null;
                $anode[5]["_available"] = true;
                $anode[5]["_left_this_month_sales"] = null;
                $anode[5]["_right_this_month_sales"] = null;
                $anode[5]["_dist_pairing_ledger"] = null;
                $anode[5]["_accumulate_left"] = null;
                $anode[5]["_accumulate_right"] = null;
                $anode[5]["_today_left"] = null;
                $anode[5]["_today_right"] = null;
                $anode[5]["_carry_left"] = null;
                $anode[5]["_carry_right"] = null;
                $anode[5]["_sales_left"] = null;
                $anode[5]["_sales_right"] = null;
            } else {
                $distDB = $this->getDistributorInformation($leftFivePlacement->getDistributorCode());
                $distOne = $this->getPlacementDistributorInformation($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $distTwo = $this->getPlacementDistributorInformation($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[5]["distCode"] = $leftFivePlacement->getDistributorCode();
                $anode[5]["_self"] = $distDB;
                $anode[5]["_left"] = null;
                $anode[5]["_right"] = null;
                $anode[5]["_available"] = false;
                $anode[5]["_left_this_month_sales"] = $this->getThisMonthSales($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[5]["_right_this_month_sales"] = $this->getThisMonthSales($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[5]["_dist_pairing_ledger"] = $this->queryDistPairing($leftFivePlacement->getDistributorId());

                $anode[5]["_accumulate_left"] = $this->getLegTotalMember($distOne);
                $anode[5]["_accumulate_right"] = $this->getLegTotalMember($distTwo);
                //                $anode[5]["_accumulate_left"] = $this->getAccumulateGroupBvs($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                //                $anode[5]["_accumulate_right"] = $this->getAccumulateGroupBvs($leftFivePlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[5]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[5]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[5]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[5]["_today_left"];
                $anode[5]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[5]["_today_right"];
                $anode[5]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
                $anode[5]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);
            }
            if ($rightSixPlacement == null) {
                $anode[6]["distCode"] = "";
                $anode[6]["_self"] = new MlmDistributor();
                $anode[6]["_left"] = null;
                $anode[6]["_right"] = null;
                $anode[6]["_available"] = true;
                $anode[6]["_left_this_month_sales"] = null;
                $anode[6]["_right_this_month_sales"] = null;
                $anode[6]["_dist_pairing_ledger"] = null;
                $anode[6]["_accumulate_left"] = null;
                $anode[6]["_accumulate_right"] = null;
                $anode[6]["_today_left"] = null;
                $anode[6]["_today_right"] = null;
                $anode[6]["_carry_left"] = null;
                $anode[6]["_carry_right"] = null;
                $anode[6]["_sales_left"] = null;
                $anode[6]["_sales_right"] = null;
            } else {
                $distDB = $this->getDistributorInformation($rightSixPlacement->getDistributorCode());
                $distOne = $this->getPlacementDistributorInformation($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $distTwo = $this->getPlacementDistributorInformation($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[6]["distCode"] = $rightSixPlacement->getDistributorCode();
                $anode[6]["_self"] = $distDB;
                $anode[6]["_left"] = null;
                $anode[6]["_right"] = null;
                $anode[6]["_available"] = false;
                $anode[6]["_left_this_month_sales"] = $this->getThisMonthSales($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[6]["_right_this_month_sales"] = $this->getThisMonthSales($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[6]["_dist_pairing_ledger"] = $this->queryDistPairing($rightSixPlacement->getDistributorId());
                $anode[6]["_accumulate_left"] = $this->getLegTotalMember($distOne);
                $anode[6]["_accumulate_right"] = $this->getLegTotalMember($distTwo);
                //                $anode[6]["_accumulate_left"] = $this->getAccumulateGroupBvs($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_LEFT);
                //                $anode[6]["_accumulate_right"] = $this->getAccumulateGroupBvs($rightSixPlacement->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[6]["_today_left"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_LEFT);
                $anode[6]["_today_right"] = $this->getTodaySales($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT);
                $anode[6]["_carry_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null) - $anode[6]["_today_left"];
                $anode[6]["_carry_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null) - $anode[6]["_today_right"];
                $anode[6]["_sales_left"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_LEFT, null);
                $anode[6]["_sales_right"] = $this->findPairingLedgers($distDB->getDistributorId(), Globals::PLACEMENT_RIGHT, null);
            }
        }

        $this->distcode = $distcode;
        $this->anode = $anode;
        $this->colorArr = $this->getRankColorArr();

        $isTop = false;
        if (strtoupper($distcode) == strtoupper($this->getUser()->getAttribute(Globals::SESSION_USERNAME))) {
            $isTop = true;
        }
        $this->isTop = $isTop;

        if ($this->getUser()->getAttribute(Globals::SESSION_PLACEMENT_TREE_PASSWORD_REQUIRED, false) == false) {
            $this->setTemplate('placementTreeInList');
        } else if ($pageDirection == "stat") {
            $this->setTemplate('placementTreeStat');
        }
    }

    public function executePendingMemberList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();

        /******   total records  *******/
        $c = new Criteria();
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $c->add(MlmDistributorPeer::PLACEMENT_TREE_LEVEL, null, Criteria::ISNULL);
        $c->add(MlmDistributorPeer::TREE_UPLINE_DIST_ID, null, Criteria::ISNULL);
        $c->add(MlmDistributorPeer::PLACEMENT_TREE_STRUCTURE, null, Criteria::ISNULL);
        $totalRecords = MlmDistributorPeer::doCount($c);

        /******   total filtered records  *******/
        if ($this->getRequestParameter('filterFullname') != "") {
            $c->addAnd(MlmDistributorPeer::FULL_NAME, "%" . $this->getRequestParameter('filterFullname') . "%", Criteria::LIKE);
        }
        if ($this->getRequestParameter('filterNickname') != "") {
            $c->addAnd(MlmDistributorPeer::NICKNAME, "%" . $this->getRequestParameter('filterNickname') . "%", Criteria::LIKE);
        }
        $totalFilteredRecords = MlmDistributorPeer::doCount($c);

        /******   sorting  *******/
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                if ("asc" == $this->getRequestParameter('sSortDir_' . $i)) {
                    $c->addAscendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                } else {
                    $c->addDescendingOrderByColumn($aColumns[intval($this->getRequestParameter('iSortCol_' . $i))]);
                }
            }
        }

        /******   pagination  *******/
        $pager = new sfPropelPager('MlmDistributor', $limit);
        $pager->setCriteria($c);
        $pager->setPage(($offset / $limit) + 1);
        $pager->init();

        foreach ($pager->getResults() as $result) {
            $arr[] = array(
                $result->getDistributorId() == null ? "" : $result->getDistributorId(),
                $result->getDistributorId() == null ? "" : $result->getDistributorId(),
                $result->getCreatedOn() == null ? "" : $result->getActiveDatetime(),
                $result->getDistributorCode() == null ? "" : $result->getDistributorCode(),
                $result->getFullName() == null ? "" : $result->getFullName(),
                $result->getNickname() == null ? "" : $result->getNickname(),
                $result->getIc() == null ? "" : $result->getIc(),
                $result->getRankCode() == null ? "" : $result->getRankCode(),
            );
        }
        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeReloadTopup()
    {
        $usdToMyr = 3.4;
        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_USD_TO_MYR);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $usdToMyr = $settingDB->getSettingValue();
        }
        $this->usdToMyr = $usdToMyr;

        $ledgerEpointBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ledgerEpointBalance = $ledgerEpointBalance;

        $distributorDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->distributorDB = $distributorDB;

        $mt4Amount = $this->getRequestParameter('mt4Amount');
        //$pointNeeded = $this->getRequestParameter('mt4Amount') * $usdToMyr;
        $pointNeeded = $this->getRequestParameter('mt4Amount');
        $mt4UserName = $distributorDB->getMt4UserName();

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);

        if ($mt4Amount > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if ($pointNeeded > $ledgerEpointBalance) {
                $this->setFlash('errorMsg', "In-sufficient e-Point");

            } elseif (strtoupper($tbl_user->getUserpassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
                $this->setFlash('errorMsg', "Invalid Security password");

            } elseif ($mt4UserName == "") {
                $this->setFlash('errorMsg', "Invalid MT4 ID.");

            } else {
                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TOPUP_MT4);
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($pointNeeded);
                $tbl_account_ledger->setBalance($ledgerEpointBalance - $pointNeeded);
                $tbl_account_ledger->setRemark("MT4 Fund :" . $mt4Amount);
                //$tbl_account_ledger->setRemark("MT4 Fund :".$mt4Amount.", CONVERSION RATE :".$usdToMyr);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $mlmMt4ReloadFund = new MlmMt4ReloadFund();
                $mlmMt4ReloadFund->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mlmMt4ReloadFund->setMt4UserName($mt4UserName);
                $mlmMt4ReloadFund->setAmount($this->getRequestParameter('mt4Amount'));
                $mlmMt4ReloadFund->setStatusCode(Globals::STATUS_PENDING);
                $mlmMt4ReloadFund->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlmMt4ReloadFund->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlmMt4ReloadFund->save();

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your MT4 Fund Reload has been submitted."));

                return $this->redirect('/member/reloadTopup');
            }
        }
    }

    public function executeTransferEcash()
    {
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $processFee = 0;
        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_TRANSFER_PROCESS_FEE);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $processFee = $settingDB->getSettingValue();
        }*/
        $this->processFee = $processFee;

        if ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('ecashAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if (($this->getRequestParameter('ecashAmount') + $processFee) > $ledgerAccountBalance) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient MT4 Credit Amount"));

            } elseif (strtoupper($appUser->getUserPassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));

            } elseif (strtoupper($this->getRequestParameter('sponsorId')) == $this->getUser()->getAttribute(Globals::SESSION_USERNAME)) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("You are not allow to transfer to own account."));

            } elseif ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('ecashAmount') > 0) {

                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getRequestParameter('sponsorId'));
                $existDist = MlmDistributorPeer::doSelectOne($c);

                $toAccount = $this->getAccountBalance($existDist->getDistributorId(), Globals::ACCOUNT_TYPE_ECASH);

                $toId = $existDist->getDistributorId();
                $toCode = $existDist->getDistributorCode();
                $toName = $existDist->getNickname();
                $toBalance = $toAccount->getBalance();
                $fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
                $fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);
                $fromName = $this->getUser()->getAttribute(Globals::SESSION_NICKNAME);
                $fromBalance = $ledgerAccountBalance;

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setDistId($fromId);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO);
                $mlm_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ")");
                $mlm_account_ledger->setCredit(0);
                $mlm_account_ledger->setDebit($this->getRequestParameter('ecashAmount'));
                $mlm_account_ledger->setBalance($fromBalance - $this->getRequestParameter('ecashAmount'));
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                //$this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($toId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM . " " . $fromCode . " (" . $fromName . ")");
                $tbl_account_ledger->setCredit($this->getRequestParameter('ecashAmount'));
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($toBalance + $this->getRequestParameter('ecashAmount'));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                //$this->revalidateAccount($toId, Globals::ACCOUNT_TYPE_ECASH);

                // ******       processing fees      ****************
                /*$tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($fromId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ") PROCESS CHARGES");
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($processFee);
                $tbl_account_ledger->setBalance($fromBalance - ($this->getRequestParameter('ecashAmount') + $processFee));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);*/

                // ******       company account      ****************
                /*$c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
                $c->addAnd(MlmAccountPeer::DIST_ID, Globals::SYSTEM_COMPANY_DIST_ID);
                $companyAccount = MlmAccountPeer::doSelectOne($c);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE . " " . $fromCode . " -> " . $toCode);
                $tbl_account_ledger->setCredit($processFee);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($companyAccount->getBalance() + $processFee);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_ECASH);*/

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Transfer success"));

                return $this->redirect('/member/transferEcash');
            }
        }
    }

    public function executeTransferEpoint()
    {
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $processFee = 0;
        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_TRANSFER_PROCESS_FEE);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $processFee = $settingDB->getSettingValue();
        }*/
        $this->processFee = $processFee;

        if ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('epointAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $appUser = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            $sponsorId = $this->getRequestParameter('sponsorId');

            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
            $existDist = MlmDistributorPeer::doSelectOne($c);

            $array = explode(',', Globals::STATUS_ACTIVE . "," . Globals::STATUS_PENDING);
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorId);
            $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $this->getUser()->getAttribute(Globals::SESSION_DISTID) . "|%", Criteria::LIKE);
            $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
            $existUser = MlmDistributorPeer::doSelectOne($c);

            if (!$existUser && $existDist) {
                $c = new Criteria();
                $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
                $c->add(MlmDistributorPeer::TREE_STRUCTURE, "%|" . $existDist->getDistributorId() . "|%", Criteria::LIKE);
                $c->add(MlmDistributorPeer::STATUS_CODE, $array, Criteria::IN);
                $existUser = MlmDistributorPeer::doSelectOne($c);

                if (!$existUser) {
                    $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid User ID."));
                    return $this->redirect('/member/transferEpoint');
                }
            }

            if (($this->getRequestParameter('epointAmount') + $processFee) > $ledgerAccountBalance) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient e-Point"));
                return $this->redirect('/member/transferEpoint');

            } elseif (strtoupper($appUser->getUserPassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));
                return $this->redirect('/member/transferEpoint');

            } elseif (strtoupper($this->getRequestParameter('sponsorId')) == $this->getUser()->getAttribute(Globals::SESSION_USERNAME)) {

                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("You are not allow to transfer to own account."));
                return $this->redirect('/member/transferEpoint');

            } elseif ($this->getRequestParameter('sponsorId') <> "" && $this->getRequestParameter('epointAmount') > 0) {
                $epointBalance = $this->getAccountBalance($existDist->getDistributorId(), Globals::ACCOUNT_TYPE_EPOINT);

                $toId = $existDist->getDistributorId();
                $toCode = $existDist->getDistributorCode();
                $toName = $existDist->getNickname();
                $toBalance = $epointBalance;
                $fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
                $fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);
                $fromName = $this->getUser()->getAttribute(Globals::SESSION_NICKNAME);
                $fromBalance = $ledgerAccountBalance;

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $mlm_account_ledger->setDistId($fromId);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO);
                $mlm_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode);
                $mlm_account_ledger->setCredit(0);
                $mlm_account_ledger->setDebit($this->getRequestParameter('epointAmount'));
                $mlm_account_ledger->setBalance($fromBalance - $this->getRequestParameter('epointAmount'));
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                //$this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_EPOINT);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId($toId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM . " " . $fromCode . " (" . $fromName . ")");
                $tbl_account_ledger->setCredit($this->getRequestParameter('epointAmount'));
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($toBalance + $this->getRequestParameter('epointAmount'));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                //$this->revalidateAccount($toId, Globals::ACCOUNT_TYPE_EPOINT);

                // ******       processing fees      ****************
                /*$tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($fromId);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO . " " . $toCode . " (" . $toName . ") PROCESS CHARGES");
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($processFee);
                $tbl_account_ledger->setBalance($fromBalance - ($this->getRequestParameter('ecashAmount') + $processFee));
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);*/

                // ******       company account      ****************
                /*$c = new Criteria();
                $c->add(MlmAccountPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
                $c->addAnd(MlmAccountPeer::DIST_ID, Globals::SYSTEM_COMPANY_DIST_ID);
                $companyAccount = MlmAccountPeer::doSelectOne($c);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_PROCESS_CHARGE . " " . $fromCode . " -> " . $toCode);
                $tbl_account_ledger->setCredit($processFee);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($companyAccount->getBalance() + $processFee);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_EPOINT);*/

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Transfer success"));

                return $this->redirect('/member/transferEpoint');
            }
        }
    }

    public function executeEcashLog()
    {
    }

    public function executeEpointLog()
    {
    }

    public function executePvLog()
    {
    }

    public function executeMaintenanceLog()
    {
    }

    public function executeFetchAnnouncementById()
    {
        $arr = "";
        if ($this->getRequestParameter('announcementId') <> "") {
            $announcement = MlmAnnouncementPeer::retrieveByPk($this->getRequestParameter('announcementId'));

            if ($announcement) {
                $title = $announcement->getTitle();
                $content = $announcement->getContent();
                if ($this->getUser()->getCulture() == 'cn') {
                    $title = $announcement->getTitleCn();
                    $content = $announcement->getContentCn();
                }
                $arr = array(
                    'title' => $title,
                    'content' => $content
                );
            }
        }

        echo json_encode($arr);
        return sfView::HEADER_ONLY;
    }

    public function executeLoginPassword()
    {
        if ($this->getRequestParameter('oldPassword')) {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $c->add(AppUserPeer::USERPASSWORD2, $this->getRequestParameter('changePasswordSecurityPassword'));
            $exist = AppUserPeer::doSelectOne($c);

            if (!$exist) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Security password is not valid."));
                return $this->redirect('/member/viewProfile');
            }

            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $c->add(AppUserPeer::USERPASSWORD, $this->getRequestParameter('oldPassword'));
            $exist = AppUserPeer::doSelectOne($c);

            if (!$exist) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Old password is not valid."));
            } else {
                $exist->setUserpassword($this->getRequestParameter('newPassword'));
                $exist->setKeepPassword($this->getRequestParameter('newPassword'));
                $exist->save();
                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Password updated"));
            }
            //return $this->redirect('/member/loginPassword');
        }
        return $this->redirect('/member/viewProfile');
    }

    public function executeTransactionPassword()
    {
        if ($this->getRequestParameter('oldSecurityPassword')) {
            $c = new Criteria();
            $c->add(AppUserPeer::USER_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));
            $c->add(AppUserPeer::USERPASSWORD2, $this->getRequestParameter('oldSecurityPassword'));
            $exist = AppUserPeer::doSelectOne($c);

            if (!$exist) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Old Security password is not valid."));
            } else {
                $exist->setUserpassword2($this->getRequestParameter('newSecurityPassword'));
                $exist->setKeepPassword2($this->getRequestParameter('newSecurityPassword'));
                $exist->save();
                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Security Password updated"));
            }
            //return $this->redirect('/member/transactionPassword');
        }
        return $this->redirect('/member/viewProfile');
    }

    public function executeAnnouncement()
    {
        $announcement = MlmAnnouncementPeer::retrieveByPK($this->getRequestParameter('id'));
        $this->forward404Unless($announcement);

        $this->announcement = $announcement;
    }

    public function executeSponsorTree()
    {
        $id = $this->getUser()->getAttribute(Globals::SESSION_DISTID);
        $distinfo = MlmDistributorPeer::retrieveByPk($id);
        $this->distinfo = $distinfo;
        $this->hasChild = $this->checkHasChild($distinfo->getDistributorId());

        /*********************/
        /* Search Function
         * ********************/
        $fullName = $this->getRequestParameter('fullName');
        $arrTree = array();

        if ($fullName != "") {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $fullName);
            $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $distinfo = MlmDistributorPeer::doSelectOne($c);

            if (!$distinfo) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Username is not exist."));
                return $this->redirect('/member/sponsorTree');
            }

            $this->distinfo = $distinfo;
            $this->hasChild = $this->checkHasChild($distinfo->getDistributorId());
        }

        $color = "blue";
        $packageName = "";

        $package = MlmPackagePeer::retrieveByPK($distinfo->getRankId());
        if ($package) {
            $color = $package->getColor();
            $packageName = $package->getPackageName();
        }
        if ($distinfo->getStatusCode() != Globals::STATUS_ACTIVE) {
            $headColor = "black";
        }
        $this->headColor = $color;
        $this->arrTree = $arrTree;
        $this->fullName = $fullName;
        $this->packageName = $packageName;

        $c = new Criteria();
        $c->add(MlmPackagePeer::PACKAGE_ID, 8, Criteria::LESS_EQUAL);
        $this->packageDBs = MlmPackagePeer::doSelect($c);
    }

    public function executeManipulateSponsorTree()
    {
        $parentId = $this->getRequestParameter('root');
        $arrTree = array();
        $html = "";
        if ($parentId != "") {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $parentId);
            //$c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $dists = MlmDistributorPeer::doSelect($c);

            $idx = 0;
            $count = count($dists);
            foreach ($dists as $dist)
            {
                $idx++;
                $hasChild = $this->checkHasChild($dist->getDistributorId());

                $treeLine = "tree-controller-lplus-line";
                $treeLine2 = "tree-controller-lplus-right";
                $treeLineNoChild = "tree-controller-t-line";
                $treeLineNoChild2 = "tree-controller-t-right";
                $treeControllerWrap = "tree-controller-wrap";
                $img = "<img class='tree-plus-button' src='/css/network/plus.png'>";
                if ($idx == $count) {
                    $treeLineNoChild = "tree-controller-l-line";
                    $treeLineNoChild2 = "tree-controller-l-right";
                    $treeControllerWrap = "tree-controller-l-wrap";
                }

                if ($hasChild) {
                } else {
                    $img = "";
                    $treeLine = $treeLineNoChild;
                    $treeLine2 = $treeLineNoChild2;
                }

                $headColor = "blue";
                $packageName = "";

                $package = MlmPackagePeer::retrieveByPK($dist->getRankId());
                if ($package) {
                    $headColor = $package->getColor();
                    $packageName = $package->getPackageName();
                }
                if ($dist->getStatusCode() != Globals::STATUS_ACTIVE) {
                    $headColor = "black";
                }
                $html .= "<div class='" . $treeControllerWrap . "'>
                        <div class='controller-node-con'>
                            <div class='tree-controller " . $treeLine . "'>
                                <div class='tree-controller-in " . $treeLine2 . "'>
                                    " . $img . "
                                </div>
                            </div>
                            <div class='node-info-raw' id='node-id-" . $dist->getDistributorId() . "'>
                                <div class='node-info'>
                                    <span class='user-rank'><img
                                            src='/css/network/" . $headColor . "_head.png'></span>
                                    <span class='user-id'>" . $dist->getDistributorCode() . "</span>
                                    <span class='user-joined'>" . $this->getContext()->getI18N()->__("Joined") . " " . date('Y-m-d', strtotime($dist->getActiveDatetime())) . "</span>
                                    <span class='user-joined'>" . $this->getContext()->getI18N()->__($dist->getStatusCode()) . "</span>
                                </div>
                            </div>
                        </div>";
                if ($hasChild) {
                    $html .= "<div id='node-wrapper-" . $dist->getDistributorId() . "' class='ajax-more'></div>";
                }
                $html .= "</div>";
            }
        }


        //echo json_encode($arrTree);
        echo $html;
        return sfView::HEADER_ONLY;
    }

    public function executeManipulateSponsorTree_old()
    {
        $parentId = $this->getRequestParameter('root');
        $arrTree = array();
        if ($parentId != "") {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $parentId);
            $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
            $dists = MlmDistributorPeer::doSelect($c);

            $idx = 0;
            $colorArr = $this->getRankColorArr();

            foreach ($dists as $dist)
            {
                $arrTree[$idx]["text"] = "<span class='user-rank'><img src='/css/pages/tree/" . $colorArr[$dist->getRankId()] . "_head.png'></span><span class='user-id'>" . $dist->getDistributorCode() . "</span><span class='user-joined'>" . $dist->getFullName() . "</span><span class='user-joined'> Joined " . date('Y-m-d', strtotime($dist->getActiveDatetime())) . "</span><span class='user-joined'>" . $dist->getRankCode() . "</span>";
                $arrTree[$idx]["id"] = $dist->getDistributorId();
                $arrTree[$idx]["hasChildren"] = $this->checkHasChild($dist->getDistributorId());
                $idx++;
            }
        }


        echo json_encode($arrTree);
        return sfView::HEADER_ONLY;
    }

    public function executeEcashWithdrawal()
    {
        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $withdrawAmount = $this->getRequestParameter('ecashAmount');
        $processFee = 5;

        /*if ($withdrawAmount <= 1000) {
            $processFee = 30;
        } else {
            $processFee = 60;
        }*/

        if ($this->getRequestParameter('ecashAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if (($withdrawAmount) > $ledgerAccountBalance) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient e-Wallet"));

            } elseif (strtoupper($tbl_user->getUserpassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));

            } elseif ($withdrawAmount > 0) {
                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($withdrawAmount);
                $tbl_account_ledger->setBalance($ledgerAccountBalance - $withdrawAmount);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                //$this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

                // ******       company account      ****************
                $companyEcashBalance = $this->getAccountBalance(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_ECASH);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId(Globals::SYSTEM_COMPANY_DIST_ID);
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);
                $tbl_account_ledger->setRemark(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL . " " . $this->getUser()->getAttribute(Globals::SESSION_USERNAME));
                $tbl_account_ledger->setCredit($processFee);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($companyEcashBalance + $processFee);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                //$this->revalidateAccount(Globals::SYSTEM_COMPANY_DIST_ID, Globals::ACCOUNT_TYPE_ECASH);

                $tbl_ecash_withdraw = new MlmEcashWithdraw();
                $tbl_ecash_withdraw->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_ecash_withdraw->setDeduct($withdrawAmount);
                $tbl_ecash_withdraw->setAmount($withdrawAmount - $processFee);
                $tbl_ecash_withdraw->setStatusCode(Globals::WITHDRAWAL_PENDING);
                $tbl_ecash_withdraw->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_ecash_withdraw->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_ecash_withdraw->save();

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your e-Wallet withdrawal has been submitted."));

                return $this->redirect('/member/ecashWithdrawal');
            }
        }
    }

    public function executeMt4Withdrawal()
    {
        //$usdToMyr = 3.4;
        $usdToMyr = 1;
        $handlingCharge = 0;
        $handlingChargeInUsd = 0;

        /*$c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_USD_TO_MYR);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $usdToMyr = $settingDB->getSettingValue();
        }*/
        $this->usdToMyr = $usdToMyr;

        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_MT4_HANDLING_FEE);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $handlingCharge = $settingDB->getSettingValue();
        }
        $this->handlingCharge = $handlingCharge;

        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, Globals::SETTING_MT4_HANDLING_FEE_USD);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $handlingChargeInUsd = $settingDB->getSettingValue();
        }
        $this->handlingChargeInUsd = $handlingChargeInUsd;

        $distributorDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->distributorDB = $distributorDB;

        if ($this->getRequestParameter('mt4Amount') > 0 && $this->getRequestParameter('transactionPassword') <> "" && $this->getRequestParameter('paymentType') <> "") {
            $tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if (strtoupper($tbl_user->getUserpassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));

            } else if ($distributorDB->getMt4UserName() == null || $distributorDB->getMt4UserName() == "") {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid MT4 ID."));

            } else {
                $paymentType = $this->getRequestParameter('paymentType');
                $usdAmount = $this->getRequestParameter('mt4Amount');
                $mt4Id = $distributorDB->getMt4UserName();

                $mt4Withdraw = new MlmMt4Withdraw();
                $mt4Withdraw->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $mt4Withdraw->setMt4UserName($mt4Id);
                $mt4Withdraw->setStatusCode(Globals::WITHDRAWAL_PENDING);

                $minHandlingFee = 0;
                $myrAmount = 0;
                $handlingFee = 0;
                $currencyCode = "USD";
                $grandAmount = 0;

                /*if ($paymentType == "BANK") {
                    $currencyCode = "MYR";

                    $usdCurrency = $usdToMyr;
                    $minHandlingFee = $handlingChargeInUsd * $usdCurrency;
                    $myrAmount = $usdAmount * $usdCurrency;
                    $handlingFee = floor($myrAmount * $usdCurrency / 100);
                    if ($handlingFee < $minHandlingFee)
                        $handlingFee = $minHandlingFee;

                    $grandAmount = $myrAmount - $handlingFee;

                    $mt4Withdraw->setAmountRequested($myrAmount);
                    $mt4Withdraw->setRemarks("MT4 Fund :".$usdAmount);
                } elseif ($paymentType == "VISA") {*/
                $currencyCode = "USD";

                $minHandlingFee = floor($usdAmount * $handlingCharge / 100);
                if ($minHandlingFee < $handlingChargeInUsd)
                    $handlingFee = $handlingChargeInUsd;
                else
                    $handlingFee = $minHandlingFee;

                $grandAmount = $usdAmount - $handlingFee;

                $mt4Withdraw->setAmountRequested($usdAmount);
                //}

                $mt4Withdraw->setHandlingFee($handlingFee);
                $mt4Withdraw->setGrandAmount($grandAmount);
                $mt4Withdraw->setPaymentType($paymentType);
                $mt4Withdraw->setCurrencyCode($currencyCode);

                $mt4Withdraw->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mt4Withdraw->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mt4Withdraw->save();

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Your MT4 withdrawal has been submitted."));

                return $this->redirect('/member/mt4Withdrawal');
            }
        }
    }

    public function executeBonusDetails()
    {
        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);

        $joinDate = $distDB->getActiveDatetime();

        $dsb = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_DRB);
        $pipsBonus = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_PIPS_BONUS);
        $creditRefunds = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_CREDIT_REFUND);
        $fundManagements = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_FUND_MANAGEMENT);
        $pairingBonus = $this->getCommissionBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::COMMISSION_TYPE_GDB);
        $specialBonus = 0;
        $totalLotTraded = 0;

        $this->dsb = number_format($dsb, 2);
        $this->pipsBonus = number_format($pipsBonus, 2);
        $this->creditRefund = number_format($creditRefunds, 2);
        $this->fundManagement = number_format($fundManagements, 2);
        $this->pairingBonus = number_format($pairingBonus, 2);
        $this->specialBonus = number_format($specialBonus, 2);
        $this->totalLotTraded = number_format($totalLotTraded, 2);

        $this->total = number_format($dsb + $pipsBonus + $creditRefunds + $fundManagements + $pairingBonus + $specialBonus, 2);

        /* *************************
         *  PIPS DETAIL
         * **************************/
        $currentMonth = date('m');
        $currentYear = date('Y');

        $anode = array();

        $idx = 0;
        if ($joinDate != null) {
            $joinMonth = date('m', strtotime($joinDate));
            $joinYear = date('Y', strtotime($joinDate));
            for ($x = intval($joinYear); $x <= intval($currentYear); $x++) {
                if ($x != $currentYear) {
                    for ($i = intval($joinMonth); $i <= 12; $i++) {
                        $anode[$idx]["year"] = $x;
                        $anode[$idx]["month"] = $i;
                        $anode[$idx]["rb_bonus"] = $this->getRbDetailByMonth($distDB->getDistributorId(), $i, $x);
                        $anode[$idx]["paring_bonus"] = $this->getPairingDetailByMonth($distDB->getDistributorId(), $i, $x);
                        $idx++;
                    }
                } else {
                    if ($joinYear != $currentYear) {
                        $joinMonth = 1;
                    }
                    for ($i = intval($joinMonth); $i <= intval($currentMonth); $i++) {
                        $anode[$idx]["year"] = $x;
                        $anode[$idx]["month"] = $i;
                        $anode[$idx]["rb_bonus"] = $this->getRbDetailByMonth($distDB->getDistributorId(), $i, $x);
                        $anode[$idx]["paring_bonus"] = $this->getPairingDetailByMonth($distDB->getDistributorId(), $i, $x);
                        $idx++;
                    }
                }
            }
        }
        $this->anode = $anode;
    }

    public function executeProfile()
    {
    }

    public function executeRegistration()
    {
    }

    public function executeVerifyNickName()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::NICKNAME, $this->getRequestParameter('nickName'));
        $exist = MlmDistributorPeer::doSelectOne($c);

        if ($exist) {
            echo 'false';
        } else {
            echo 'true';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeVerifyUserName()
    {
        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $this->getRequestParameter('userName'));
        $exist = AppUserPeer::doSelectOne($c);

        if ($exist) {
            echo 'false';
        } else {
            echo 'true';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeVerifyCardNumber()
    {
        $c = new Criteria();
        $c->add(MlmMemberCardPeer::CARD_NUMBER, $this->getRequestParameter('cardNumber'));
        $c->add(MlmMemberCardPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $exist = MlmMemberCardPeer::doSelectOne($c);

        if ($exist) {
            echo 'true';
        } else {
            echo 'false';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeVerifyFullName()
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::FULL_NAME, $this->getRequestParameter('fullname'));
        $exist = MlmDistributorPeer::doSelectOne($c);

        if ($exist) {
            echo 'false';
        } else {
            echo 'true';
        }

        return sfView::HEADER_ONLY;
    }

    public function executeViewProfile()
    {
        if ($this->getUser()->getAttribute(Globals::SESSION_SECURITY_PASSWORD_REQUIRED, false) == false) {
            return $this->redirect('/member/securityPasswordRequired');
        }

        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $distDB->getUplineDistId());
        $sponsor = MlmDistributorPeer::doSelectOne($c);
        if (!$sponsor) {
            $sponsor = new MlmDistributor();
        }

        $this->sponsor = $sponsor;
        $this->distDB = $distDB;
    }

    public function executeBankInformation()
    {
        $distDB = MlmDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $this->forward404Unless($distDB);

        $this->distDB = $distDB;

        $this->bankName2 = $this->getAppSetting(Globals::SETTING_BANK_NAME_2);
        $this->bankSwiftCode2 = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE_2);
        $this->iban2 = $this->getAppSetting(Globals::SETTING_IBAN_2);
        $this->bankAccountHolder2 = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER_2);
        $this->bankAccountNumber2 = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER_2);
        $this->cityOfBank2 = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK_2);
        $this->countryOfBank2 = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK_2);

        $this->bankName = $this->getAppSetting(Globals::SETTING_BANK_NAME);
        $this->bankSwiftCode = $this->getAppSetting(Globals::SETTING_BANK_SWIFT_CODE);
        $this->iban = $this->getAppSetting(Globals::SETTING_IBAN);
        $this->bankAccountHolder = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_HOLDER);
        $this->bankAccountNumber = $this->getAppSetting(Globals::SETTING_BANK_ACCOUNT_NUMBER);
        $this->cityOfBank = $this->getAppSetting(Globals::SETTING_CITY_OF_BANK);
        $this->countryOfBank = $this->getAppSetting(Globals::SETTING_COUNTRY_OF_BANK);
    }

    public function executeDailyBonus()
    {
        $con = Propel::getConnection(MlmDailyBonusLogPeer::DATABASE_NAME);
        try {
            $con->begin();
            print_r("Start<br>");
            print_r("Company Commission<br>");

            //$monthAdded = 1; // testing for this month
            $monthAdded = 0; // production

            $queryStartDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded - 1), 1, date("Y")));
            $queryDate = date("Y-m-d", mktime(0, 0, 0, (date("m") + $monthAdded), 0, date("Y")));

            print_r("Start Date:".$queryStartDate."<br>");
            print_r("End Date:".$queryDate."<br>");
            //$queryDate = date("Y-m-d", mktime(0, 0, 0, date("m"), 0, date("Y")));

            $c = new Criteria();
            $c->addDescendingOrderByColumn(MlmPackagePeer::SALES_COMMISSION);
            $maxSalesCommissionPackageDB = MlmPackagePeer::doSelectOne($c);
            $maxSalesCommission = $maxSalesCommissionPackageDB->getSalesCommission();

            $c = new Criteria();
            $distDBs = MlmDistributorPeer::doSelect($c);

            $companyBonusForManagers = array();
            $companyBonusForSupervisors = array();
            $companyBonusForMasterDealers = array();
            foreach ($distDBs as $distDB) {
                $distId = $distDB->getDistributorId();
                $totalPV = $this->getTotalPV($distDB->getDistributorId(), $queryDate);
                print_r($distDB->getDistributorId().":".$totalPV);
                print_r("<br>");
                if ($totalPV > 0) {
                    // Sales Commission ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    $salesCommissionPackageDB = MlmPackagePeer::retrieveByPK($distDB->getRankId());
                    $salesCommission = $salesCommissionPackageDB->getSalesCommission();
                    //$totalSalesBonus = $salesCommission * $totalAmount / 100;
                    $totalSalesBonus = $salesCommission * $totalPV / 100;

                    $distAccountEcashBalance = $this->getAccountBalance($distId, Globals::ACCOUNT_TYPE_ECASH);

                    $mlm_account_ledger = new MlmAccountLedger();
                    $mlm_account_ledger->setDistId($distId);
                    $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                    $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_SALES_COMMISSION);
                    $mlm_account_ledger->setRemark("TOTAL PV: " . $totalPV . ", COMMISSION: " . $salesCommission . "%");
                    $mlm_account_ledger->setCredit($totalSalesBonus);
                    $mlm_account_ledger->setDebit(0);
                    $mlm_account_ledger->setBalance($distAccountEcashBalance + $totalSalesBonus);
                    $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->save();

                    $mlm_account_ledger = new MlmAccountLedger();
                    $mlm_account_ledger->setDistId($distId);
                    $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_PV);
                    $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_MONTHLY_BONUS);
                    $mlm_account_ledger->setRemark("");
                    $mlm_account_ledger->setCredit(0);
                    $mlm_account_ledger->setDebit($totalPV);
                    $mlm_account_ledger->setBalance(0);
                    $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $mlm_account_ledger->save();

                    $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($distId, Globals::COMMISSION_TYPE_SALES_COMMISSION);

                    $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                    $sponsorDistCommissionledger->setDistId($distId);
                    $sponsorDistCommissionledger->setCredit($totalSalesBonus);
                    $sponsorDistCommissionledger->setDebit(0);
                    $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                    $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $totalSalesBonus);
                    $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_SALES_COMMISSION);
                    $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                    $sponsorDistCommissionledger->setRemark("TOTAL PV: " . $totalPV . ", COMMISSION: " . $salesCommission . "%");
                    $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                    $sponsorDistCommissionledger->save();

                    // Group development bonus ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    if ($distDB->getUplineDistId() != null) {
                        $uplineDistId = $distDB->getUplineDistId();
                        $uplineDistDB = MlmDistributorPeer::retrieveByPK($uplineDistId);

                        $uplinePackageDB = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
                        $uplineSalesCommission = $uplinePackageDB->getSalesCommission();

                        $checkCommission = true;
                        while ($checkCommission == true) {
                            if ($salesCommission < $uplineSalesCommission) {
                                $overridingBonus = $uplineSalesCommission - $salesCommission;
                                $salesCommission = $uplineSalesCommission;

                                $totalSalesBonus = $overridingBonus * $totalPV / 100;

                                $distAccountEcashBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_ECASH);

                                $mlm_account_ledger = new MlmAccountLedger();
                                $mlm_account_ledger->setDistId($uplineDistId);
                                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_OVERRIDING_BONUS);
                                $mlm_account_ledger->setRemark("TOTAL PV: " . $totalPV . ", COMMISSION: " . $overridingBonus . "%");
                                $mlm_account_ledger->setCredit($totalSalesBonus);
                                $mlm_account_ledger->setDebit(0);
                                $mlm_account_ledger->setBalance($distAccountEcashBalance + $totalSalesBonus);
                                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $mlm_account_ledger->save();

                                $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($uplineDistId, Globals::COMMISSION_TYPE_SALES_COMMISSION);

                                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                                $sponsorDistCommissionledger->setDistId($uplineDistId);
                                $sponsorDistCommissionledger->setCredit($totalSalesBonus);
                                $sponsorDistCommissionledger->setDebit(0);
                                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                                $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $totalSalesBonus);
                                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_OVERRIDING_BONUS);
                                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                                $sponsorDistCommissionledger->setRemark("TOTAL PV: " . $totalPV . ", COMMISSION: " . $overridingBonus . "%");
                                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                $sponsorDistCommissionledger->save();
                            }

                            if ($salesCommission >= $maxSalesCommission) {
                                $checkCommission = false;
                                break;
                            }

                            $uplineDistId = $uplineDistDB->getUplineDistId();

                            if ($uplineDistId == null) {
                                break;
                            }

                            $salesCommissionDistDB = MlmDistributorPeer::retrieveByPK($uplineDistId);
                            $salesCommissionPackageDB = MlmPackagePeer::retrieveByPK($salesCommissionDistDB->getRankId());
                            $uplineSalesCommission = $salesCommissionPackageDB->getSalesCommission();
                        }
                    }

                    // Leadership Commission && Company Bonus ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    //var_dump($this->isQualifyForLeadershipBonus($distId, $queryStartDate, $queryDate));
                    //print_r("<br>");
                    if ($this->isQualifyForLeadershipBonus($distId, $queryStartDate, $queryDate)) {
                        if ($distDB->getRankId() > 1) {
                            print_r("<br>");
                            print_r("<br>");
                            print_r("<br>");
                            print_r("Leadership Commission ++++++++++++<br>");
                            print_r($distId." isQualifyForLeadershipBonus totalDirectMemberPV +++++++++++++ <br>");
                            print_r("<br>");
                            $c = new Criteria();
                            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distId);
                            $totalSponsor = MlmDistributorPeer::doCount($c);

                            $totalLevel = $totalSponsor;
                            if ($totalSponsor > 5) {
                                $totalLevel = 5;
                            }
                            print_r("Total level:".$totalLevel."<br>");
                            /*$c = new Criteria();
                          $c->add(MlmDistributorPeer::TREE_STRUCTURE, "|%" . $distId . "%|", Criteria::LIKE);
                          $c->add(MlmDistributorPeer::RANK_ID, $distDB->getRankId(), Criteria::GREATER_EQUAL);
                          $c->addAscendingOrderByColumn(MlmDistributorPeer::TREE_LEVEL);
                          $sponsorDists = MlmDistributorPeer::doSelect($c);*/

                            $query = "SELECT dist.distributor_id, dist.distributor_code, dist.tree_structure
                                        , pack.sales_commission
                                    FROM mlm_distributor dist
                                        LEFT JOIN mlm_package pack ON pack.package_id = dist.rank_id
                                    WHERE dist.tree_structure LIKE '%|" . $distId . "|%' AND pack.sales_commission >= ".$salesCommission."
                                        ORDER BY dist.tree_level DESC";

                            $arrays = array();
                            $distCodeArrays = array();
                            $idx = 0;
                            $connection = Propel::getConnection();
                            $statement = $connection->prepareStatement($query);
                            $resultset = $statement->executeQuery();
                            while ($resultset->next()) {
                                $arr = $resultset->getRow();
                                $isAllow = true;
                                if ($idx > 0) {
                                    $count = $this->substrCountArray($arrays, $arr['tree_structure']);

                                    print_r("Count:".$count."<br>");
                                    if ($count > $totalLevel) {
                                        $isAllow = false;
                                    }
                                }
                                if ($isAllow) {
                                    $arrays[$idx] = $arr['distributor_id'];
                                    $distCodeArrays[$idx++] = $arr['distributor_code'];
                                }
                            }
                            var_dump($arrays);
                            print_r("<br>");
                            var_dump($distCodeArrays);
                            print_r("<br>");
                            $excludingTreeStructure = "";
                            for ($idx = 0; $idx < count($arrays); $idx++) {
                                //print_r("dist Code:".$distCodeArrays[$idx]);
                                //print_r("<br>");
                                //print_r("dist ID:".$arrays[$idx]);
                                //print_r("<br>");
                                $totalGroupPV = $this->getGroupPV($arrays[$idx], $queryDate, $excludingTreeStructure);

                                $totalLeadershipBonus = $totalGroupPV * Globals::LEADERSHIP_BONUS_PERCENTAGE / 100;
                                if ($totalLeadershipBonus > 0) {

                                    $distAccountEcashBalance = $this->getAccountBalance($distId, Globals::ACCOUNT_TYPE_ECASH);

                                    $mlm_account_ledger = new MlmAccountLedger();
                                    $mlm_account_ledger->setDistId($distId);
                                    $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                                    $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_LEADERSHIP_BONUS);
                                    $mlm_account_ledger->setRemark("TOTAL PV: " . $totalGroupPV . ", MEMBER GROUP: " . $distCodeArrays[$idx]);
                                    $mlm_account_ledger->setCredit($totalLeadershipBonus);
                                    $mlm_account_ledger->setDebit(0);
                                    $mlm_account_ledger->setBalance($distAccountEcashBalance + $totalLeadershipBonus);
                                    $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $mlm_account_ledger->save();

                                    $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($distId, Globals::COMMISSION_TYPE_LEADERSHIP_BONUS);

                                    $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                                    $sponsorDistCommissionledger->setDistId($distId);
                                    $sponsorDistCommissionledger->setCredit($totalLeadershipBonus);
                                    $sponsorDistCommissionledger->setDebit(0);
                                    $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                                    $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $totalLeadershipBonus);
                                    $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_LEADERSHIP_BONUS);
                                    $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                                    $sponsorDistCommissionledger->setRemark("TOTAL PV: " . $totalGroupPV . ", MEMBER GROUP: " . $distCodeArrays[$idx]);
                                    $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $sponsorDistCommissionledger->save();
                                }
                                $excludingTreeStructure .= " AND tree_structure NOT LIKE '%|".$arrays[$idx]."|%'";
                            }
                        }

                        // Company Bonus validation ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                        print_r("<br>");
                        print_r("<br>");
                        print_r("<br>");
                        print_r($distId."::Company Bonus validation ++++++++++++<br>");
                        if ($salesCommissionPackageDB->getPackageId() > 5) {
                            print_r("Entitle Company Bonus ++++++++++++<br>");
                            $c = new Criteria();
                            $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distId);
                            $sponsorDists = MlmDistributorPeer::doSelect($c);

                            $companyBonusSalesTarget = 200000;
                            $singleLegMax = 100000;
                            if ($salesCommissionPackageDB->getPackageId() == 6) {
                                $companyBonusSalesTarget = 50000;
                                $singleLegMax = 25000;
                            } else if ($salesCommissionPackageDB->getPackageId() == 7) {
                                $companyBonusSalesTarget = 100000;
                                $singleLegMax = 50000;
                            } else if ($salesCommissionPackageDB->getPackageId() == 8) {
                                $companyBonusSalesTarget = 200000;
                                $singleLegMax = 100000;
                            }
                            $totalGroupPv = 0;
                            foreach ($sponsorDists as $sponsorDist) {
                                $singleLegPv = $this->getTotalGroupPV($sponsorDist->getDistributorId(), $queryStartDate, $queryDate);

                                if ($singleLegPv > $singleLegMax) {
                                    $singleLegPv = $singleLegMax;
                                }

                                $totalGroupPv += $singleLegPv;

                                print_r($sponsorDist->getDistributorId()."===> total group sales:".$sponsorDist->getDistributorId().":".$totalGroupPv);
                                print_r("<br>");
                                print_r("sales target:".$companyBonusSalesTarget);
                                print_r("<br>");
                                if (($totalGroupPv + $totalPV) >= $companyBonusSalesTarget) {
                                    if ($salesCommissionPackageDB->getPackageId() == 6) {
                                        $companyBonusForMasterDealers[count($companyBonusForMasterDealers)] = $distId;
                                    } else if ($salesCommissionPackageDB->getPackageId() == 7) {
                                        $companyBonusForMasterDealers[count($companyBonusForMasterDealers)] = $distId;
                                        $companyBonusForSupervisors[count($companyBonusForSupervisors)] = $distId;
                                    } else if ($salesCommissionPackageDB->getPackageId() == 8) {
                                        $companyBonusForMasterDealers[count($companyBonusForMasterDealers)] = $distId;
                                        $companyBonusForSupervisors[count($companyBonusForSupervisors)] = $distId;
                                        $companyBonusForManagers[count($companyBonusForManagers)] = $distId;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            print_r("Start Company Bonus Calculation ++++++++++++<br>");
            var_dump($companyBonusForManagers);
            print_r("<br>");
            var_dump($companyBonusForSupervisors);
            print_r("<br>");
            var_dump($companyBonusForMasterDealers);
            print_r("<br>");
            $companyTotalSales = $this->getTotalGroupPV(null, $queryStartDate, $queryDate);

            $companyBonusManagerAmount = $companyTotalSales * 1 / 100 / count($companyBonusForManagers);
            $companyBonusSupervisorAmount = $companyTotalSales * 1.5 / 100 / count($companyBonusForSupervisors);
            $companyBonusMasterAmount = $companyTotalSales * 2.5 / 100 / count($companyBonusForMasterDealers);

            for ($idx = 0; $idx < count($companyBonusForManagers); $idx++) {
                $distId = $companyBonusForManagers[$idx];
                $distAccountEcashBalance = $this->getAccountBalance($distId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($distId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_COMPANY_BONUS);
                $mlm_account_ledger->setRemark("(Manager Bonus) Company Total Sales: " . $companyTotalSales);
                $mlm_account_ledger->setCredit($companyBonusManagerAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $companyBonusManagerAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($distId, Globals::COMMISSION_TYPE_COMPANY_BONUS);

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($distId);
                $sponsorDistCommissionledger->setCredit($companyBonusManagerAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $companyBonusManagerAmount);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_COMPANY_BONUS);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                $sponsorDistCommissionledger->setRemark("(Manager Bonus) Company Total Sales: " . $companyTotalSales);
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();
            }
            for ($idx = 0; $idx < count($companyBonusForSupervisors); $idx++) {
                $distId = $companyBonusForSupervisors[$idx];
                $distAccountEcashBalance = $this->getAccountBalance($distId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($distId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_COMPANY_BONUS);
                $mlm_account_ledger->setRemark("(Supervisor Bonus) Company Total Sales: " . $companyTotalSales);
                $mlm_account_ledger->setCredit($companyBonusSupervisorAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $companyBonusSupervisorAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($distId, Globals::COMMISSION_TYPE_COMPANY_BONUS);

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($distId);
                $sponsorDistCommissionledger->setCredit($companyBonusSupervisorAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $companyBonusSupervisorAmount);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_COMPANY_BONUS);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                $sponsorDistCommissionledger->setRemark("(Supervisor Bonus) Company Total Sales: " . $companyTotalSales);
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();
            }
            for ($idx = 0; $idx < count($companyBonusForMasterDealers); $idx++) {
                $distId = $companyBonusForMasterDealers[$idx];
                $distAccountEcashBalance = $this->getAccountBalance($distId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($distId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_COMPANY_BONUS);
                $mlm_account_ledger->setRemark("(Master Dealer Bonus) Company Total Sales: " . $companyTotalSales);
                $mlm_account_ledger->setCredit($companyBonusMasterAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $companyBonusMasterAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                $sponsorDistCommissionLedgerDB = $this->getCommissionBalance($distId, Globals::COMMISSION_TYPE_COMPANY_BONUS);

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($distId);
                $sponsorDistCommissionledger->setCredit($companyBonusMasterAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($sponsorDistCommissionLedgerDB + $companyBonusMasterAmount);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_COMPANY_BONUS);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_MONTHLY_BONUS);
                $sponsorDistCommissionledger->setRemark("(Master Dealer Bonus) Company Total Sales: " . $companyTotalSales);
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();
            }

            //$bonusDate = $dateUtil->formatDate("Y-m-d", $dateUtil->addDate($bonusDate, 1, 0, 0));
            $mlm_daily_bonus_log = new MlmDailyBonusLog();
            $mlm_daily_bonus_log->setAccessIp($this->getRequest()->getHttpHeader('addr', 'remote'));
            $mlm_daily_bonus_log->setBonusType(Globals::DAILY_BONUS_LOG_TYPE_DAILY);
            $mlm_daily_bonus_log->setBonusDate(date("Y-m-d H:i:s"));
            $mlm_daily_bonus_log->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_daily_bonus_log->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_daily_bonus_log->save();

            $con->commit();
        } catch (PropelException $e) {
            $con->rollback();
            //throw $e;
        }

        print_r("Done");
        return sfView::HEADER_ONLY;
    }

    function retrieveGmailMailAttachment()
    {
        $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
        $username = 'finance@ronuva.com';
        $password = 'RONUVAtemp';

        var_dump("start reading email");
        /* try to connect */
        $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
        /* grab emails */
        $emails = imap_search($inbox, 'UNSEEN');
        /* if emails are returned, cycle through each... */
        if ($emails) {

            /* begin output var */
            $remarks = '';

            /* put the newest emails on top */
            rsort($emails);

            /* for every email... */
            foreach ($emails as $email_number) {
                /* get information specific to this email */
                $overview = imap_fetch_overview($inbox, $email_number, 0);
                $message = imap_fetchbody($inbox, $email_number, 2);
                $structure = imap_fetchstructure($inbox, $email_number);

                //pre($overview);
                $remarks .= 'subject:' . $overview[0]->subject;
                $remarks .= ', from:' . $overview[0]->from;
                $remarks .= ', date:' . $overview[0]->date;

                $emailSubject = $overview[0]->subject;

                $timeStamp = strtotime($emailSubject); //"06-10-2011 14:28" or "06/10/2011 14:28"

                $tradedDate = date("d-m-Y", $timeStamp); // outputs 06-10
                $attachments = array();
                if (isset($structure->parts) && count($structure->parts)) {
                    for ($i = 0; $i < count($structure->parts); $i++) {
                        $attachments[$i] = array(
                            'is_attachment' => false,
                            'filename' => '',
                            'name' => '',
                            'attachment' => '');

                        if ($structure->parts[$i]->ifdparameters) {
                            foreach ($structure->parts[$i]->dparameters as $object) {
                                if (strtolower($object->attribute) == 'filename') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['filename'] = $object->value;
                                }
                            }
                        }

                        if ($structure->parts[$i]->ifparameters) {
                            foreach ($structure->parts[$i]->parameters as $object) {
                                if (strtolower($object->attribute) == 'name') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['name'] = $object->value;
                                }
                            }
                        }

                        if ($attachments[$i]['is_attachment']) {
                            $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1);
                            if ($structure->parts[$i]->encoding == 3) { // 3 = BASE64
                                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                            }
                            elseif ($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
                                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                            }
                        }
                    } // for($i = 0; $i < count($structure->parts); $i++)
                } // if(isset($structure->parts) && count($structure->parts))

                if (count($attachments) != 0) {
                    foreach ($attachments as $at) {
                        if ($at[is_attachment] == 1) {
                            $pos = strrpos($at[filename], "csv");
                            if ($pos === false) { // note: three equal signs
                                // not found...
                            } else {
                                $con = Propel::getConnection(MlmDailyPipsFilePeer::DATABASE_NAME);
                                try {
                                    $con->begin();

                                    $fileName = date("YmdGis") . "_" . $at[filename];
                                    file_put_contents(sfConfig::get('sf_upload_dir') . '/daily_pips/' . $fileName, $at[attachment]);

                                    $physicalDirectory = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'daily_pips' . DIRECTORY_SEPARATOR . $fileName;
                                    $file_handle = fopen($physicalDirectory, "rb");

                                    $mlmDailyPipsFile = new MlmDailyPipsFile();
                                    $mlmDailyPipsFile->setFileType("PIPS");
                                    $mlmDailyPipsFile->setFileSrc($physicalDirectory);
                                    $mlmDailyPipsFile->setFileName($fileName);
                                    $mlmDailyPipsFile->setContentType("application/csv");
                                    $mlmDailyPipsFile->setStatusCode(Globals::STATUS_ACTIVE);
                                    $mlmDailyPipsFile->setRemarks($remarks);
                                    $mlmDailyPipsFile->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $mlmDailyPipsFile->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                    $mlmDailyPipsFile->save();

                                    while (!feof($file_handle)) {
                                        $line_of_text = fgets($file_handle);
                                        $parts = explode('=', $line_of_text);
                                        //print_r($line_of_text);
                                        $string = $parts[0] . $parts[1];
                                        $arr = explode(';', $string);

                                        $status = Globals::STATUS_PIPS_CSV_ACTIVE;
                                        $remarks = "";

                                        $mlm_pip_csv = new MlmDailyPipsCsv();
                                        $mlm_pip_csv->setFileId($mlmDailyPipsFile->getFileId());
                                        $mlm_pip_csv->setPipsString($string);

                                        if (count($arr) == 12) {
                                            if (is_numeric($arr[0])) {
                                                $idx = 0;
                                                $mlm_pip_csv->setTradedDatetime($tradedDate);
                                                $mlm_pip_csv->setLoginId($arr[0]);
                                                $mlm_pip_csv->setLoginName($arr[1]);
                                                $mlm_pip_csv->setBalance($arr[12]);
                                                $mlm_pip_csv->setCredit($arr[5]);
                                                $mlm_pip_csv->setCommissions($arr[7]);
                                                $mlm_pip_csv->setTaxes($arr[8]);
                                                $mlm_pip_csv->setStorage($arr[10]);
                                                $mlm_pip_csv->setProfit($arr[11]);
                                                //$mlm_pip_csv->setInterest($arr[$idx++]);
                                                //$mlm_pip_csv->setTax($arr[8]);
                                                //$mlm_pip_csv->setUnrealizedpl($arr[$idx++]);
                                                //$mlm_pip_csv->setEquity($arr[$idx++]);
                                                /*$mlm_pip_csv->setLoginId($arr[$idx++]);
                                                $mlm_pip_csv->setLoginName($arr[$idx++]);
                                                $mlm_pip_csv->setBalance($arr[$idx++]);
                                                $mlm_pip_csv->setCredit($arr[$idx++]);
                                                $mlm_pip_csv->setCommissions($arr[$idx++]);
                                                $mlm_pip_csv->setTaxes($arr[$idx++]);
                                                $mlm_pip_csv->setStorage($arr[$idx++]);
                                                $mlm_pip_csv->setProfit($arr[$idx++]);
                                                $mlm_pip_csv->setInterest($arr[$idx++]);
                                                $mlm_pip_csv->setTax($arr[$idx++]);
                                                $mlm_pip_csv->setUnrealizedpl($arr[$idx++]);
                                                $mlm_pip_csv->setEquity($arr[$idx++]);*/
                                                $mlm_pip_csv->setStatusCode($status);
                                                $mlm_pip_csv->setRemarks($remarks);
                                                $mlm_pip_csv->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                                $mlm_pip_csv->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                                $mlm_pip_csv->save();
                                            } else {
                                                $status = Globals::STATUS_PIPS_CSV_ERROR;
                                                $remarks = "FIRST ELEMENT NOT NUMERIC";

                                                $mlm_pip_csv->setStatusCode($status);
                                                $mlm_pip_csv->setRemarks($remarks);
                                                $mlm_pip_csv->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                                $mlm_pip_csv->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                                $mlm_pip_csv->save();
                                            }
                                        } else {
                                            $status = Globals::STATUS_PIPS_CSV_ERROR;
                                            $remarks = "ARRAY NOT EQUAL TO 12";

                                            $mlm_pip_csv->setStatusCode($status);
                                            $mlm_pip_csv->setRemarks($remarks);
                                            $mlm_pip_csv->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                            $mlm_pip_csv->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                                            $mlm_pip_csv->save();
                                        }
                                    }
                                    $con->commit();
                                } catch (PropelException $e) {
                                    $con->rollback();
                                    //throw $e;
                                }
                            }
                        }
                    }
                }
            }
            //echo $output;
        }

        /* close the connection */
        imap_close($inbox);
    }

    public function executeDownloadMt4()
    {
        $response = $this->getResponse();
        $response->clearHttpHeaders();
        $response->addCacheControlHttpHeader('Cache-control', 'must-revalidate, post-check=0, pre-check=0');
        $response->setContentType('application/exe');
        $response->setHttpHeader('Content-Transfer-Encoding', 'binary', TRUE);
        $response->setHttpHeader('Content-Disposition', 'attachment; filename=pro4setup.exe', TRUE);
        $response->sendHttpHeaders();
        readfile(sfConfig::get('sf_upload_dir') . "/pro4setup.exe");
        return sfView::NONE;
    }

    public function executeConvertEcashToEpoint()
    {
        $ledgerAccountBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->ledgerAccountBalance = $ledgerAccountBalance;

        $epointAmount = $this->getRequestParameter('epointAmount');

        if ($this->getRequestParameter('epointAmount') > 0 && $this->getRequestParameter('transactionPassword') <> "") {
            $tbl_user = AppUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

            if ($epointAmount > $ledgerAccountBalance) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient e-Wallet"));

            } elseif (strtoupper($tbl_user->getUserpassword2()) <> strtoupper($this->getRequestParameter('transactionPassword'))) {
                $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Invalid Security password"));

            } elseif ($epointAmount > 0) {
                $ledgerEPointBalance = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_CONVERT_EPOINT);
                $tbl_account_ledger->setCredit(0);
                $tbl_account_ledger->setDebit($epointAmount);
                $tbl_account_ledger->setBalance($ledgerAccountBalance - $epointAmount);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                $tbl_account_ledger = new MlmAccountLedger();
                $tbl_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
                $tbl_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
                $tbl_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_CONVERT);
                $tbl_account_ledger->setCredit($epointAmount);
                $tbl_account_ledger->setDebit(0);
                $tbl_account_ledger->setBalance($ledgerEPointBalance + $epointAmount);
                $tbl_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $tbl_account_ledger->save();

                //$this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
                //$this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);

                $this->setFlash('successMsg', $this->getContext()->getI18N()->__("e-Wallet convert to e-Point successful."));

                return $this->redirect('/member/convertEcashToEpoint');
            }
        }
    }

    public function executePurchasePackage()
    {
        $pendingDistId = $this->getRequestParameter('p');

        $c = new Criteria();

        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $pendingDistId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $pendingDistDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($pendingDistDB);

        $c = new Criteria();
        $c->add(MlmPackagePeer::PUBLIC_PURCHASE, 1);
        $packageDBs = MlmPackagePeer::doSelect($c);

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->pendingDistDB = $pendingDistDB;
        $this->packageDBs = $packageDBs;
    }

    public function executePackageUpgrade()
    {
        $distDB = MlmDistributorPeer::retrieveByPK($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        if ($distDB->getRankId() > 1) {
            return $this->redirect('/member/summary');
        }

        $c = new Criteria();
        //$c->add(MlmPackagePeer::PUBLIC_PURCHASE, 1);
        $c->add(MlmPackagePeer::PACKAGE_ID, 2);
        $packageDBs = MlmPackagePeer::doSelect($c);

        $this->systemCurrency = $this->getAppSetting(Globals::SETTING_SYSTEM_CURRENCY);
        $this->pointAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_EPOINT);
        $this->ecashAvailable = $this->getAccountBalance($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);
        $this->packageDBs = $packageDBs;
    }

    /************************************************************************************************************************
     * function
     ************************************************************************************************************************/
    function getDistributorIdByCode($sponsorCode)
    {
        $userId = 0;

        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $sponsorCode);
        //$c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $existUser = MlmDistributorPeer::doSelectOne($c);

        if ($existUser) {
            $userId = $existUser->getDistributorId();
        }

        return $userId;
    }

    function getDistributorInformation($distCode)
    {
        $c = new Criteria();

        $c->add(MlmDistributorPeer::DISTRIBUTOR_CODE, $distCode);
        //$c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $distDB = MlmDistributorPeer::doSelectOne($c);
        if (!$distDB) {
            return null;
        }

        return $distDB;
    }

    function getCommissionBalance($distributorId, $commissionType)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_commission_ledger WHERE dist_id = " . $distributorId . " AND commission_type = '" . $commissionType . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function revalidatePairing($distributorId, $leftRight)
    {
        $balance = $this->getPairingBalance($distributorId, $leftRight);

        $c = new Criteria();
        $c->add(MlmDistPairingPeer::DIST_ID, $distributorId);
        $tbl_account = MlmDistPairingPeer::doSelectOne($c);

        if (!$tbl_account) {
            $tbl_account = new MlmDistPairing();
            $tbl_account->setDistId($distributorId);
            $tbl_account->setLeftBalance(0);
            $tbl_account->setRightBalance(0);
        }
        if (Globals::PLACEMENT_LEFT == $leftRight) {
            $tbl_account->setLeftBalance($balance);
        } else if (Globals::PLACEMENT_RIGHT == $leftRight) {
            $tbl_account->setRightBalance($balance);
        }

        $tbl_account->save();
    }

    function getPairingBalance($distributorId, $leftRight)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId . " AND left_right = '" . $leftRight . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        $count = 0;
        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getAccountBalance($distributorId, $accountType)
    {
        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_account_ledger WHERE dist_id = " . $distributorId . " AND account_type = '" . $accountType . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function checkHasChild($distId)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::UPLINE_DIST_ID, $distId);
        $c->addAnd(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        $list = MlmDistributorPeer::doSelect($c);
        if ($list) {
            return true;
        }
        return false;
    }

    function doActivateAccount($uplineDistId, $sponsorId, $packageId, $paymentType)
    {
        $packageDB = MlmPackagePeer::retrieveByPK($packageId);
        $this->forward404Unless($packageDB);
        $packageAmount = $packageDB->getPrice();

        /* ****************************************************
         * get distributor last account ledger epoint balance
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmAccountLedgerPeer::DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));
        if ("epoint" == $paymentType) {
            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_EPOINT);
        } else if ("ecash" == $paymentType) {
            $c->add(MlmAccountLedgerPeer::ACCOUNT_TYPE, Globals::ACCOUNT_TYPE_ECASH);
        }
        $c->addDescendingOrderByColumn(MlmAccountLedgerPeer::CREATED_ON);
        $accountLedgerDB = MlmAccountLedgerPeer::doSelectOne($c);
        if (!$accountLedgerDB) {
            $accountLedgerDB = new MlmAccountLedger();
            $accountLedgerDB->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            $accountLedgerDB->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
            $accountLedgerDB->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
            $accountLedgerDB->setRemark("");
            $accountLedgerDB->setCredit(0);
            $accountLedgerDB->setDebit(0);
            $accountLedgerDB->setBalance(0);
            $accountLedgerDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $accountLedgerDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $accountLedgerDB->save();
        }

        $sponsorAccountBalance = $accountLedgerDB->getBalance();

        /* ****************************************************
         * get sponsored distributor and user
         * ***************************************************/
        $c = new Criteria();
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $sponsorId);
        $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_PENDING);
        $sponsoredDistDB = MlmDistributorPeer::doSelectOne($c);
        $this->forward404Unless($sponsoredDistDB);

        $userDB = AppUserPeer::retrieveByPK($sponsoredDistDB->getUserId());
        $this->forward404Unless($userDB);

        /* ****************************************************
         * update sponsored distributor and user
         * ***************************************************/
        $sponsoredDistDB->setRankId($packageDB->getPackageId());
        $sponsoredDistDB->setRankCode($packageDB->getPackageName());
        $sponsoredDistDB->setInitRankId($packageDB->getPackageId());
        $sponsoredDistDB->setInitRankCode($packageDB->getPackageName());
        $sponsoredDistDB->setStatusCode(Globals::STATUS_ACTIVE);
        $sponsoredDistDB->setPackagePurchaseFlag("Y");
        $sponsoredDistDB->setActiveDatetime(date("Y/m/d h:i:s A"));
        $sponsoredDistDB->setActivatedBy($this->getUser()->getAttribute(Globals::SESSION_DISTID));
        $sponsoredDistDB->save();

        $userDB->setStatusCode(Globals::STATUS_ACTIVE);
        $userDB->save();

        /**************************************/
        /*  Direct REFERRAL Bonus For Upline
        /**************************************/
        $uplineDistDB = MlmDistributorPeer::retrieveByPK($uplineDistId);
        if ($uplineDistDB) {
            $uplineDistPackage = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
            $directSponsorPercentage = $uplineDistPackage->getCommission();
            $directSponsorBonusAmount = $directSponsorPercentage * $packageDB->getPrice() / 100;
            $totalBonusPayOut = $directSponsorPercentage;

            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_ECASH, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            $this->doSaveAccount($sponsorId, Globals::ACCOUNT_TYPE_EPOINT, 0, 0, Globals::ACCOUNT_LEDGER_ACTION_REGISTER, "");
            /* ****************************************************
           * Update upline distributor account
           * ***************************************************/
            $sponsorAccountBalance = $sponsorAccountBalance - $packageDB->getPrice();

            $mlm_account_ledger = new MlmAccountLedger();
            $mlm_account_ledger->setDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));
            if ("epoint" == $paymentType) {
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_EPOINT);
            } else if ("ecash" == $paymentType) {
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
            }
            $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);
            $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $packageDB->getPackageName() . ")");
            $mlm_account_ledger->setCredit(0);
            $mlm_account_ledger->setDebit($packageDB->getPrice());
            $mlm_account_ledger->setBalance($sponsorAccountBalance);
            $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $mlm_account_ledger->save();

            /******************************/
            /*  Direct Sponsor Bonus
            /******************************/
            $firstForDRB = true;
            while ($totalBonusPayOut <= Globals::TOTAL_BONUS_PAYOUT) {
                $distAccountEcashBalance = $this->getAccountBalance($uplineDistId, Globals::ACCOUNT_TYPE_ECASH);

                $mlm_account_ledger = new MlmAccountLedger();
                $mlm_account_ledger->setDistId($uplineDistId);
                $mlm_account_ledger->setAccountType(Globals::ACCOUNT_TYPE_ECASH);
                $mlm_account_ledger->setTransactionType(Globals::ACCOUNT_LEDGER_ACTION_DRB);
                $mlm_account_ledger->setRemark("PACKAGE PURCHASE (" . $packageDB->getPackageName() . ") " . $directSponsorPercentage . "% (" . $sponsoredDistDB->getDistributorCode() . ")");
                $mlm_account_ledger->setCredit($directSponsorBonusAmount);
                $mlm_account_ledger->setDebit(0);
                $mlm_account_ledger->setBalance($distAccountEcashBalance + $directSponsorBonusAmount);
                $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $mlm_account_ledger->save();

                //$this->revalidateAccount($uplineDistId, Globals::ACCOUNT_TYPE_ECASH);

                /******************************/
                /*  Commission
                /******************************/
                $c = new Criteria();
                $c->add(MlmDistCommissionLedgerPeer::DIST_ID, $uplineDistId);
                $c->add(MlmDistCommissionLedgerPeer::COMMISSION_TYPE, Globals::COMMISSION_TYPE_DRB);
                $c->addDescendingOrderByColumn(MlmDistCommissionLedgerPeer::CREATED_ON);
                $sponsorDistCommissionLedgerDB = MlmDistCommissionLedgerPeer::doSelectOne($c);

                $dsbBalance = 0;
                if ($sponsorDistCommissionLedgerDB)
                    $dsbBalance = $sponsorDistCommissionLedgerDB->getBalance();

                $sponsorDistCommissionledger = new MlmDistCommissionLedger();
                $sponsorDistCommissionledger->setDistId($uplineDistId);
                $sponsorDistCommissionledger->setCommissionType(Globals::COMMISSION_TYPE_DRB);
                $sponsorDistCommissionledger->setTransactionType(Globals::COMMISSION_LEDGER_REGISTER);
                $sponsorDistCommissionledger->setCredit($directSponsorBonusAmount);
                $sponsorDistCommissionledger->setDebit(0);
                $sponsorDistCommissionledger->setStatusCode(Globals::STATUS_ACTIVE);
                $sponsorDistCommissionledger->setBalance($dsbBalance + $directSponsorBonusAmount);
                if ($firstForDRB == true) {
                    $sponsorDistCommissionledger->setRemark("DRB FOR PACKAGE PURCHASE " . $directSponsorPercentage . "% (" . $packageDB->getPackageName() . ") for " . $sponsoredDistDB->getDistributorCode());
                    $firstForDRB = false;
                } else {
                    $sponsorDistCommissionledger->setRemark("GRB FOR PACKAGE PURCHASE " . $directSponsorPercentage . "% (" . $packageDB->getPackageName() . ") for " . $sponsoredDistDB->getDistributorCode());
                }
                $sponsorDistCommissionledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
                $sponsorDistCommissionledger->save();

                //$this->revalidateCommission($uplineDistId, Globals::COMMISSION_TYPE_DRB);
                //var_dump("==>1");
                if ($totalBonusPayOut < Globals::TOTAL_BONUS_PAYOUT) {
                    //var_dump("==>2");
                    $checkCommission = true;
                    $uplineDistId = $uplineDistDB->getUplineDistId();
                    while ($checkCommission == true) {
                        //var_dump("==>3**".$uplineDistId);
                        $uplineDistDB = MlmDistributorPeer::retrieveByPK($uplineDistId);

                        //var_dump("==>3$$".$uplineDistId);
                        $this->forward404Unless($uplineDistDB);
                        $uplineDistPackage = MlmPackagePeer::retrieveByPK($uplineDistDB->getRankId());
                        $directSponsorPercentage = $uplineDistPackage->getCommission();

                        if ($directSponsorPercentage > $totalBonusPayOut) {
                            //var_dump("==>6");
                            $directSponsorPercentage = $directSponsorPercentage - $totalBonusPayOut;
                            $totalBonusPayOut += $directSponsorPercentage;
                            if ($totalBonusPayOut > Globals::TOTAL_BONUS_PAYOUT) {
                                //var_dump("==>7");
                                $directSponsorPercentage = $directSponsorPercentage - ($totalBonusPayOut - Globals::TOTAL_BONUS_PAYOUT);
                            }
                        } else {
                            //var_dump("==>8");
                            $uplineDistId = $uplineDistDB->getUplineDistId();
                            continue;
                        }

                        $directSponsorBonusAmount = $directSponsorPercentage * $packageDB->getPrice() / 100;
                        $checkCommission == false;
                        break;
                        //var_dump("==>9");
                    }
                } else {
                    break;
                    //var_dump("==>^^");
                }
            }
        }

    }

    function getAppSetting($parameter)
    {
        $result = "";
        $c = new Criteria();
        $c->add(AppSettingPeer::SETTING_PARAMETER, $parameter);
        $settingDB = AppSettingPeer::doSelectOne($c);
        if ($settingDB) {
            $result = $settingDB->getSettingValue();
        }
        return $result;
    }

    function doSaveAccount($distId, $accountType, $credit, $debit, $transactionType, $remarks)
    {
        $mlm_account_ledger = new MlmAccountLedger();
        $mlm_account_ledger->setDistId($distId);
        $mlm_account_ledger->setAccountType($accountType);
        $mlm_account_ledger->setTransactionType($transactionType);
        $mlm_account_ledger->setRemark($remarks);
        $mlm_account_ledger->setCredit($credit);
        $mlm_account_ledger->setDebit($debit);
        $mlm_account_ledger->setBalance($credit - $debit);
        $mlm_account_ledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_account_ledger->save();
    }

    function getPlacementDistributorInformation($uplineDistId, $placeLocation)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::TREE_UPLINE_DIST_ID, $uplineDistId);
        $c->add(MlmDistributorPeer::PLACEMENT_POSITION, $placeLocation);
        //$c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $placeDB = MlmDistributorPeer::doSelectOne($c);
        return $placeDB;
    }

    function getTotalPosition($distId, $position)
    {
        $c = new Criteria();
        $c->add(MlmDistributorPeer::PLACEMENT_POSITION, $position);
        $c->add(MlmDistributorPeer::DISTRIBUTOR_ID, $distId, Criteria::NOT_EQUAL);
        $c->add(MlmDistributorPeer::PLACEMENT_TREE_STRUCTURE, "%|" . $distId . "|%", Criteria::LIKE);
        //$c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

        $totalDis = MlmDistributorPeer::doCount($c);
        return $totalDis;
    }

    function getDsbAmount($distributorId, $date)
    {
        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_dist_commission_ledger WHERE dist_id = " . $distributorId
                 . " AND commission_type = '" . Globals::ACCOUNT_LEDGER_ACTION_DRB . "'";

        $query .= " AND created_on >= '" . $date . " 00:00:00'";
        $query .= " AND created_on <= '" . $date . " 23:59:59'";

        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function toFreezeAndCalculateInvestmentPackage($batchId)
    {
        $connection = Propel::getConnection();

        $query = "UPDATE mlm_dist_investment_package set bonus_release = '" . Globals::STATUS_PROCESSING . "' WHERE status_code = '" . Globals::STATUS_ACTIVE . "'
            AND bonus_release = '" . Globals::STATUS_PENDING . "' AND batch_id = " . $batchId;

        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        $query = "SELECT SUM(total_package) AS SUB_TOTAL FROM mlm_dist_investment_package
            WHERE bonus_release  = '" . Globals::STATUS_PROCESSING . "' AND batch_id = " . $batchId;

        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function unFreezeInvestmentPackage()
    {
        $connection = Propel::getConnection();

        $query = "UPDATE mlm_dist_investment_package set bonus_release = '" . Globals::STATUS_COMPLETE . "' WHERE status_code = '" . Globals::STATUS_ACTIVE . "'
            AND bonus_release = '" . Globals::STATUS_PROCESSING . "'";

        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
    }

    function updateDistPairingLeader($distId, $position, $debit, $remark = "PAIRED", $transactionType = Globals::PAIRING_LEDGER_PAIRED)
    {
        /*$c = new Criteria();
        $c->add(MlmDistPairingLedgerPeer::DIST_ID, $distId);
        $c->add(MlmDistPairingLedgerPeer::LEFT_RIGHT, $position);
        $c->addDescendingOrderByColumn(MlmDistPairingLedgerPeer::CREATED_ON);
        $sponsorDistPairingLedgerDB = MlmDistPairingLedgerPeer::doSelectOne($c);

        $legBalance = 0;
        if ($sponsorDistPairingLedgerDB) {
            $legBalance = $sponsorDistPairingLedgerDB->getBalance();
        }*/
        $legBalance = $this->findPairingLedgers($distId, $position, null);
        // update pairing balance
        $distPairingledger = new MlmDistPairingLedger();
        $distPairingledger->setDistId($distId);
        $distPairingledger->setLeftRight($position);
        $distPairingledger->setTransactionType($transactionType);
        $distPairingledger->setCredit(0);
        $distPairingledger->setDebit($debit);
        $distPairingledger->setBalance($legBalance - $debit);
        $distPairingledger->setRemark($remark);
        $distPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->save();

        $this->revalidatePairing($distId, $position);
    }

    function flushDistPairingLeader($distId, $position, $minBalance, $remark)
    {
        $distPairingledger = new MlmDistPairingLedger();
        $distPairingledger->setDistId($distId);
        $distPairingledger->setLeftRight($position);
        $distPairingledger->setTransactionType(Globals::PAIRING_LEDGER_FLUSH);
        $distPairingledger->setCredit(0);
        $distPairingledger->setDebit($minBalance);
        $distPairingledger->setBalance(0);
        $distPairingledger->setRemark($remark);
        $distPairingledger->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $distPairingledger->save();

        $this->revalidatePairing($distId, $position);
    }

    function getRbDetailByMonth($distributorId, $month, $year)
    {
        $dateUtil = new DateUtil();

        $d = $dateUtil->getMonth($month, $year);
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(bonus.credit-bonus.debit) AS SUB_TOTAL FROM mlm_dist_commission_ledger bonus
                        WHERE 1=1 "
                 . " AND bonus.commission_type = '" . Globals::COMMISSION_TYPE_DRB . "'"
                 . " AND bonus.created_on >= '" . $firstOfMonth . "' AND bonus.created_on <= '" . $lastOfMonth . "'";

        if ($distributorId != null) {
            $query = $query . " AND bonus.dist_id = " . $distributorId;
        }
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getPairingDetailByMonth($distributorId, $month, $year)
    {
        $dateUtil = new DateUtil();

        $d = $dateUtil->getMonth($month, $year);
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(bonus.credit-bonus.debit) AS SUB_TOTAL FROM mlm_dist_commission_ledger bonus
                        WHERE 1=1 "
                 . " AND bonus.commission_type = '" . Globals::COMMISSION_TYPE_GDB . "'"
                 . " AND bonus.created_on >= '" . $firstOfMonth . "' AND bonus.created_on <= '" . $lastOfMonth . "'";

        if ($distributorId != null) {
            $query = $query . " AND bonus.dist_id = " . $distributorId;
        }
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalInvestmentPackageInWallet($distId)
    {
        $query = "SELECT SUM(total_package) AS _SUM FROM mlm_dist_investment_package";

        $query .= " WHERE dist_id = " . $distId;
        $query .= " AND status_code = '" . Globals::STATUS_ACTIVE . "'";
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalPackageInTheGame()
    {
        $query = "SELECT SUM(total_package) AS _SUM FROM mlm_dist_investment_package
                WHERE status_code = '" . Globals::STATUS_ACTIVE . "'
                    AND bonus_release <> '" . Globals::STATUS_PENDING . "' ";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalCurrentInvestmentPackageSold()
    {
        $query = "SELECT SUM(total_package) AS _SUM FROM mlm_dist_investment_package";

        $query .= " WHERE status_code = '" . Globals::STATUS_ACTIVE . "' AND bonus_release = '" . Globals::STATUS_PENDING . "'";
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalInvestmentPackageSold($date)
    {
        $query = "SELECT SUM(total_package) AS _SUM FROM mlm_dist_investment_package package";

        $query .= " LEFT JOIN mlm_distributor dist ON dist.distributor_id = package.dist_id";
        $query .= " WHERE package.status_code = '" . Globals::STATUS_ACTIVE . "' AND dist.status_code = '" . Globals::STATUS_ACTIVE . "' AND package.dist_id <> " . Globals::SYSTEM_COMPANY_DIST_ID;
        if ($date != null) {
            $dateFrom = $date . " 00:00:00";
            $dateTo = $date . " 23:59:59";

            $query .= " AND package.created_on >= '" . $dateFrom . "' AND package.created_on <='" . $dateTo . "'";
        }
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalTreePackageInvested($distId)
    {
        $query = "SELECT SUM(package.total_package) AS _SUM, package.dist_id
                    FROM mlm_dist_investment_package package
                LEFT JOIN mlm_distributor dist ON dist.distributor_id = package.dist_id
                        WHERE package.status_code = '" . Globals::STATUS_ACTIVE . "'
                    AND dist.status_code = '" . Globals::STATUS_ACTIVE . "'
                    AND package.bonus_release <> '" . Globals::STATUS_PENDING . "'
                    AND tree_structure LIKE '%|" . $distId . "|%'";
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function getTotalFundManagementGain($distId)
    {
        $query = "SELECT SUM(credit - debit) AS _SUM
                    FROM mlm_account_ledger
                where dist_id = " . $distId . "
                AND account_type = '" . Globals::ACCOUNT_TYPE_ECASH . "'
                AND transaction_type = '" . Globals::ACCOUNT_LEDGER_ACTION_FUND_MANAGEMENT . "'";
        //var_dump($query);

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_SUM"] != null) {
                return $arr["_SUM"];
            } else {
                return 0;
            }
        }
        return 0;
    }

    function isQualifyForLeadershipBonus($distId, $queryStartDate, $queryEndDate)
    {
        $isQualify = false;
        $totalPV = $this->getTotalDirectSponsorPV($distId, $queryStartDate, $queryEndDate);
        $totalDirectMemberPV = $this->getTotalDirectSponsorMemberPV($distId, $queryStartDate, $queryEndDate);
        print_r("isQualifyForLeadershipBonus totalPV:".$totalPV."<br>");
        print_r("isQualifyForLeadershipBonus totalDirectMemberPV:".$totalDirectMemberPV."<br>");
        print_r("<br>");
        if (($totalPV + $totalDirectMemberPV) >= Globals::LEADERSHIP_BONUS_PV_REQUIRED) {
            $isQualify = true;
        }

        return $isQualify;
    }

    function getRankColor($packageId)
    {
        $color = "blue";

        $package = MlmPackagePeer::retrieveByPK($packageId);
        if ($package) {
            $color = $package->getColor();
        }

        return $color;
    }

    function getRankColorArr()
    {
        $packageArray = array();
        $c = new Criteria();
        $packages = MlmPackagePeer::doSelect($c);
        foreach ($packages as $package) {
            $packageArray[$package->getPackageId()] = $package->getColor();
        }

        return $packageArray;
    }

    function getLegTotalMember($distributor)
    {
        if ($distributor) {
            $c = new Criteria();
            $c->add(MlmDistributorPeer::PLACEMENT_TREE_STRUCTURE, "%|" . $distributor->getDistributorId() . "|%", Criteria::LIKE);
            $c->add(MlmDistributorPeer::STATUS_CODE, Globals::STATUS_ACTIVE);

            $totalDis = MlmDistributorPeer::doCount($c);
            return $totalDis;
        }

        return 0;
    }

    function entitiedInvestmentPackageBonus($distId)
    {
        $c = new Criteria();
        $c->add(MlmDistInvestmentPackagePeer::DIST_ID, $distId);
        $c->add(MlmDistInvestmentPackagePeer::STATUS_CODE, Globals::STATUS_ACTIVE);
        //$c->add(MlmDistInvestmentPackagePeer::BONUS_RELEASE, Globals::STATUS_COMPLETE);

        $totalInvestmentPackage = MlmDistributorPeer::doCount($c);
        if ($totalInvestmentPackage > 0)
            return true;
        return false;
    }

    function executeSendRemindationEmailForUploadAgreement()
    {
        $body = "<table width='100%' cellspacing='0' cellpadding='0' border='0' bgcolor='#939393' align='center'>
	<tbody>
		<tr>
			<td style='padding:20px 0px'>
				<table width='606' cellspacing='0' cellpadding='0' border='0' align='center' style='background:white;font-family:Arial,Helvetica,sans-serif'>
					<tbody>
						<tr>
							<td colspan='2'>
								<a target='_blank' href='http://www.ronuva.com'><img width='606' height='115' border='0' src='http://partner.ronuva.com/images/email/banner.png' alt='RONUVA'></a></td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table style='background-color:rgb(246,246,246)'>
													<tbody>
														<tr>
															<td valign='top' style='padding-top:15px;padding-left:10px'>
																<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:17px'>
												Dear our distinguished member,
<br><br>
Thank you for your support and faith in us!
<br><br>
Owning to the terms as stipulated by Forex world, please provide us your documents:
<br><br>
1)      Identification (IC / Passport, front and back at same page)
<br><br>
2)      Proof of Address (Bank / Credit Card statement, OR Water / Electric statement, OR Phone / Internet statement)
<br><br>
-          Your name, current address and the date of the latest 3 months must be shown at the statement.
<br><br>
3)      Download and sign the Forex Agreements.
<br><br>
And upload all the documents at website.
<br><br>
Note:
<br><br>
Please logon to http://partner.ronuva.com. Click “User Profile” to upload all the documents at “Upload Document”.
<br><br>
Thank you for your highly cooperation.
<br><br>
Wish you all the best.
<br><br>
<br><br>


											</font>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>


						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table style='background-color:rgb(246,246,246)'>
													<tbody>
														<tr>
															<td valign='top' style='padding-top:15px;padding-left:10px'>
																<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:17px'>
												亲爱的会员，
<br><br>
您好。
<br><br>
由于外汇的要求严谨，请您将您的文件包括：
<br><br>
1） 身份证（正反面在同一页）
<br><br>
2） 地址证明（银行/信用卡明细单，或水/电明细单，或电话/网络明细单）
<br><br>
-          明细单必须清楚列明您的姓名，目前住址及最近3个月日期。
<br><br>
3） 下载并签署外汇合约。
<br><br>
上传给公司，否则这会影响您日后的提现。
<br><br>
注：请登入http://partner.ronuva.com，点击“用户个人资料”将所有文件上传给公司（点击“上传文件”）。
<br><br>
谢谢您的鼎力合作。
<br><br>
祝：一切顺利

												<br>
											</font>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td width='606' style='font-size:0;line-height:0' bgcolor='#0080C8'>
							<img src='http://partner.ronuva.com/images/email/transparent.gif' height='1'>
							</td>
						</tr>
						<tr>
							<td width='606' style='font-size:0;line-height:0' colspan='2'>
								<img src='http://partner.ronuva.com/images/email/transparent.gif' height='10'>
							</td>
						</tr>

						<tr>
							<td width='606' style='padding:15px 15px 0px;color:rgb(153,153,153);font-size:11px' colspan='2' align='right'>
							<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
								<em>
									Best Regards,<br>
									<strong>RONUVA</strong><br>
									E mail : admin@ronuva.com
								</em>
							</font>
							<br>
							<a href='http://ronuva.com/' target='_blank'><img src='http://partner.ronuva.com/images/email/logo.png' width='254' height='87' border='0'></a>
							<br>
						</tr>

						<tr>
							<td width='606' style='padding:5px 15px 20px;color:rgb(153,153,153);font-size:11px' colspan='2'>
							<p align='justify'>
								<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
									RONUVA is managed by RONUVA Capital Limited which is authorised and regulated in the New Zealand by the Financial Services Provider. FSP Register number is 252705. Registered Office: Level 8, 10/12 Scotia Place, Suite 11, Auckland City Centre, Auckland, 1010, New Zealand. Tel (+64) 93791159, Email accounts@ronuva.com
									<br><br>RONUVA Capital Limited is a subsidiary of Royale Group Holding Inc. a public listed company in USA.
									<br><br>CONFIDENTIALITY: This e-mail and any files transmitted with it are confidential and intended solely for the use of the recipient(s) only. Any review, retransmission, dissemination or other use of, or taking any action in reliance upon this information by persons or entities other than the intended recipient(s) is prohibited. If you have received this e-mail in error please notify the sender immediately and destroy the material whether stored on a computer or otherwise.
									<br><br>DISCLAIMER: Any views or opinions presented within this e-mail are solely those of the author and do not necessarily represent those of RONUVA capital Limited, unless otherwise specifically stated. The content of this message does not constitute Investment Advice.
									<br><br>RISK WARNING: Forex, spread bets, and CFDs carry a high degree of risk to your capital and it is possible to lose more than your initial investment. Only speculate with money you can afford to lose. As with any trading, you should not engage in it unless you understand the nature of the transaction you are entering into and, the true extent of your exposure to the risk of loss. These products may not be suitable for all investors, therefore if you do not fully understand the risks involved, please seek independent advice.
								</font>
							</p>
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>";

        $sendMailService = new SendMailService();
        $subject = "RONUVA Forex Agreement 外汇合约";

        $dateUtil = new DateUtil();
        $date = $dateUtil->formatDate("Y-m-d", $dateUtil->addDate(date("Y-m-d"), -7, 0, 0));
        $arrs = $this->fetchMemberWithoutUploadDocument($date);
        foreach ($arrs as $arr) {
            $receiverEmail = $arr['email'];
            $receiverFullName = $arr['full_name'];

            //print_r($receiverFullName."<br>");
            //$sendMailService->sendMail($receiverEmail, $receiverFullName, $subject, $body);
        }
        //$sendMailService->sendMail("r9jason@gmail.com", "jason", $subject, $body);
    }

    function fetchMemberWithoutUploadDocument($date)
    {
        $dateFrom = $date . " 00:00:00";
        $dateTo = $date . " 23:59:59";

        $query = "SELECT distributor_id, distributor_code, full_name, email
	                    FROM mlm_distributor where (file_bank_pass_book is null or file_proof_of_residence is null or file_nric is null)
	                    and email is not null
	                    and active_datetime >= '" . $dateFrom . "' AND created_on <= '" . $dateTo . "'
	                    and status_code = '" . Globals::STATUS_ACTIVE . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();
        $count = 0;
        while ($resultset->next()) {
            $arr = $resultset->getRow();

            $resultArray[$count]["distributor_id"] = $arr["distributor_id"];
            $resultArray[$count]["distributor_code"] = $arr["distributor_code"];
            $resultArray[$count]["full_name"] = $arr["full_name"];
            $resultArray[$count]["email"] = $arr["email"];
            $count++;
        }
        return $resultArray;
    }

    function getGroupPV($distId, $queryDate, $excludingTreeStructure)
    {
        $credit = 0;

        $query = "SELECT SUM(ledger.credit - ledger.debit) AS SUB_TOTAL FROM mlm_account_ledger ledger
                        LEFT JOIN mlm_distributor dist ON dist.distributor_id = ledger.dist_id
                    WHERE ledger.dist_id = " . $distId . " AND ledger.account_type='" . Globals::ACCOUNT_TYPE_PV . "'";
        $query .= " AND ledger.created_on <= '" . $queryDate . " 23:59:59' ".$excludingTreeStructure;
        //var_dump($query);
        //exit();
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $credit = $arr["SUB_TOTAL"];
        }

        return $credit;
    }

    function getMaxSponsorPackagePrice($sponsorUplineDistId)
    {
        $query = "SELECT max(package.price) as MAX_PRICE
                    FROM mlm_distributor dist
                        LEFT JOIN mlm_package package ON package.package_id = dist.rank_id
                    WHERE dist.upline_dist_id = " . $sponsorUplineDistId;

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();
        $result = 0;
        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $result = $arr["MAX_PRICE"];
        }
        return $result;
    }

    function getTotalPV($distId, $queryDate)
    {
        $result = 0;
        $credit = 0;
        $debit = 0;

        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_account_ledger
                    WHERE dist_id = " . $distId . " AND account_type='" . Globals::ACCOUNT_TYPE_PV . "'";
        $query .= " AND created_on <= '" . $queryDate . " 23:59:59'";
        //var_dump($query);
        //exit();
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $credit = $arr["SUB_TOTAL"];
        }

        $query = "SELECT SUM(debit) AS SUB_TOTAL FROM mlm_account_ledger
                    WHERE dist_id = " . $distId . " AND account_type='" . Globals::ACCOUNT_TYPE_PV . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $debit = $arr["SUB_TOTAL"];
        }
        $result = $credit - $debit;

        return $result;
    }

    function getTotalDirectSponsorPV($distId, $queryStartDate, $queryEndDate)
    {
        $result = 0;
        $credit = 0;
        $debit = 0;

        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_account_ledger
                    WHERE dist_id = " . $distId . " AND account_type='" . Globals::ACCOUNT_TYPE_PV . "'";
        $query .= " AND created_on >= '" . $queryStartDate . " 00:00:00'";
        $query .= " AND created_on <= '" . $queryEndDate . " 23:59:59'";
        //var_dump($query);
        //exit();
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $credit = $arr["SUB_TOTAL"];
        }

        /*$query = "SELECT SUM(debit) AS SUB_TOTAL FROM mlm_account_ledger
                    WHERE upline_dist_id = " . $distId . " AND account_type='" . Globals::ACCOUNT_TYPE_PV . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $debit = $arr["SUB_TOTAL"];
        }*/
        $result = $credit - $debit;

        return $result;
    }

    function getTotalDirectSponsorMemberPV($distId, $queryStartDate, $queryEndDate)
    {
        $result = 0;
        $credit = 0;
        $debit = 0;

        $query = "SELECT SUM(ledger.credit) AS SUB_TOTAL FROM mlm_account_ledger ledger
                        LEFT JOIN mlm_distributor dist ON dist.distributor_id = ledger.dist_id
                    WHERE dist.upline_dist_id = " . $distId . " AND ledger.account_type='" . Globals::ACCOUNT_TYPE_PV . "'";
        $query .= " AND dist.rank_id = 1";

        if ($queryStartDate != null) {
            $query .= " AND ledger.created_on >= '" . $queryStartDate . " 00:00:00'";
        }
        if ($queryEndDate != null) {
            $query .= " AND ledger.created_on <= '" . $queryEndDate . " 23:59:59'";
        }
        //var_dump($query);
        //exit();
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $credit = $arr["SUB_TOTAL"];
        }

        /*$query = "SELECT SUM(debit) AS SUB_TOTAL FROM mlm_account_ledger
                    WHERE upline_dist_id = " . $distId . " AND account_type='" . Globals::ACCOUNT_TYPE_PV . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $debit = $arr["SUB_TOTAL"];
        }*/
        $result = $credit - $debit;

        return $result;
    }

    function getTotalGroupPV($distId, $queryStartDate, $queryEndDate)
    {
        $credit = 0;

        $query = "SELECT SUM(ledger.credit) AS SUB_TOTAL FROM mlm_account_ledger ledger
                        INNER JOIN mlm_distributor dist ON dist.distributor_id = ledger.dist_id
                    WHERE 1=1 ";

        if ($distId != null) {
            $query .= " AND dist.tree_structure like '%|" . $distId . "|%'";
        }
        $query .= " AND ledger.account_type='" . Globals::ACCOUNT_TYPE_PV . "'";
        $query .= " AND ledger.created_on >= '" . $queryStartDate . " 00:00:00'";
        $query .= " AND ledger.created_on <= '" . $queryEndDate . " 23:59:59'";
        //var_dump($query);
        //exit();
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();
        $resultArray = array();

        if ($resultset->next()) {
            $arr = $resultset->getRow();

            $credit = $arr["SUB_TOTAL"];
        }

        return $credit;
    }

    function getThisMonthSales($distributorId, $position)
    {
        /*$dateUtil = new DateUtil();

        $d = $dateUtil->getMonth();
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'"
                 . " AND transaction_type = '" . Globals::PAIRING_LEDGER_REGISTER . "'"
                 . " AND created_on >= '" . $firstOfMonth . "' AND created_on <= '" . $lastOfMonth . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }*/
        return 0;
    }

    function queryDistPairing($distributorId)
    {
        /*$c = new Criteria();
        $c->add(MlmDistPairingPeer::DIST_ID, $distributorId);
        $mlmDist = MlmDistPairingPeer::doSelectOne($c);
        if (!$mlmDist) {
            $distDB = MlmDistributorPeer::retrieveByPK($distributorId);
            $distPairingDB = new MlmDistPairing();
            $distPairingDB->setDistId($distributorId);

            $packageDB = MlmPackagePeer::retrieveByPK($distDB->getRankId());
            $this->forward404Unless($packageDB);

            $distPairingDB->setLeftBalance(0);
            $distPairingDB->setRightBalance(0);
            //$distPairingDB->setFlushLimit($packageDB->getDailyMaxPairing());
            $distPairingDB->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $distPairingDB->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
            $distPairingDB->save();
            return $distPairingDB;
        }
        return $mlmDist;*/

        return new MlmDistPairing();
    }

    function getAccumulateGroupBvs($distributorId, $position)
    {
        /*$dateUtil = new DateUtil();

        $d = $dateUtil->getMonth();
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'"
                 . " AND transaction_type = '" . Globals::PAIRING_LEDGER_REGISTER . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }*/
        return 0;
    }

    function getTodaySales($distributorId, $position)
    {
        /*$dateUtil = new DateUtil();

        $d = $dateUtil->getMonth();
        $firstOfMonth = date('Y-m-j') . " 00:00:00";
        $lastOfMonth = date('Y-m-j') . " 23:59:59";

        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'"
                 . " AND transaction_type = '" . Globals::PAIRING_LEDGER_REGISTER . "'"
                 . " AND created_on >= '" . $firstOfMonth . "' AND created_on <= '" . $lastOfMonth . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }*/

        return 0;
    }

    function findPairingLedgers($distributorId, $position, $date)
    {
        /*$query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_dist_pairing_ledger WHERE dist_id = " . $distributorId
                 . " AND left_right = '" . $position . "'";

        if ($date != null) {
            $query .= " AND created_on <= '" . $date . " 23:59:59'";
        }
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                return $arr["SUB_TOTAL"];
            } else {
                return 0;
            }
        }*/
        return 0;
    }

    function format2decimal($d)
    {
        return ceil($d * 100) / 100;
    }

    function substrCountArray($arrays, $strings)
    {
        $count = 0;
        foreach ($arrays as $substring) {
            $count += substr_count($strings, $substring);
        }
        return $count;
    }
}